From fe2b41133356382a81df1e8b46a6610758255765 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 21 May 2021 02:46:53 +0000 Subject: [PATCH 1/2] feat: added API for continuous test PiperOrigin-RevId: 374994233 Source-Link: https://github.com/googleapis/googleapis/commit/31313cb7f81b4323d25fb0a320e688a7c6c22502 Source-Link: https://github.com/googleapis/googleapis-gen/commit/e8bc2a63bb1317868576df83b7dd5bc9f3ebac84 --- owl-bot-staging/v3/MANIFEST.in | 2 + owl-bot-staging/v3/README.rst | 49 + owl-bot-staging/v3/docs/conf.py | 376 ++ .../v3/docs/dialogflowcx_v3/agents.rst | 10 + .../v3/docs/dialogflowcx_v3/entity_types.rst | 10 + .../v3/docs/dialogflowcx_v3/environments.rst | 10 + .../v3/docs/dialogflowcx_v3/experiments.rst | 10 + .../v3/docs/dialogflowcx_v3/flows.rst | 10 + .../v3/docs/dialogflowcx_v3/intents.rst | 10 + .../v3/docs/dialogflowcx_v3/pages.rst | 10 + .../security_settings_service.rst | 10 + .../v3/docs/dialogflowcx_v3/services.rst | 19 + .../dialogflowcx_v3/session_entity_types.rst | 10 + .../v3/docs/dialogflowcx_v3/sessions.rst | 6 + .../v3/docs/dialogflowcx_v3/test_cases.rst | 10 + .../transition_route_groups.rst | 10 + .../v3/docs/dialogflowcx_v3/types.rst | 7 + .../v3/docs/dialogflowcx_v3/versions.rst | 10 + .../v3/docs/dialogflowcx_v3/webhooks.rst | 10 + owl-bot-staging/v3/docs/index.rst | 7 + .../v3/google/cloud/dialogflowcx/__init__.py | 439 ++ .../v3/google/cloud/dialogflowcx/py.typed | 2 + .../google/cloud/dialogflowcx_v3/__init__.py | 440 ++ .../cloud/dialogflowcx_v3/gapic_metadata.json | 1095 +++++ .../v3/google/cloud/dialogflowcx_v3/py.typed | 2 + .../dialogflowcx_v3/services/__init__.py | 15 + .../services/agents/__init__.py | 22 + .../services/agents/async_client.py | 892 ++++ .../dialogflowcx_v3/services/agents/client.py | 1127 +++++ .../dialogflowcx_v3/services/agents/pagers.py | 140 + .../services/agents/transports/__init__.py | 33 + .../services/agents/transports/base.py | 304 ++ .../services/agents/transports/grpc.py | 485 ++ .../agents/transports/grpc_asyncio.py | 489 ++ .../services/entity_types/__init__.py | 22 + .../services/entity_types/async_client.py | 659 +++ .../services/entity_types/client.py | 846 ++++ .../services/entity_types/pagers.py | 140 + .../entity_types/transports/__init__.py | 33 + .../services/entity_types/transports/base.py | 241 + .../services/entity_types/transports/grpc.py | 356 ++ .../entity_types/transports/grpc_asyncio.py | 360 ++ .../services/environments/__init__.py | 22 + .../services/environments/async_client.py | 723 +++ .../services/environments/client.py | 919 ++++ .../services/environments/pagers.py | 262 ++ .../environments/transports/__init__.py | 33 + .../services/environments/transports/base.py | 262 ++ .../services/environments/transports/grpc.py | 407 ++ .../environments/transports/grpc_asyncio.py | 411 ++ .../services/experiments/__init__.py | 22 + .../services/experiments/async_client.py | 738 +++ .../services/experiments/client.py | 934 ++++ .../services/experiments/pagers.py | 140 + .../experiments/transports/__init__.py | 33 + .../services/experiments/transports/base.py | 269 ++ .../services/experiments/transports/grpc.py | 418 ++ .../experiments/transports/grpc_asyncio.py | 422 ++ .../services/flows/__init__.py | 22 + .../services/flows/async_client.py | 1008 ++++ .../dialogflowcx_v3/services/flows/client.py | 1243 +++++ .../dialogflowcx_v3/services/flows/pagers.py | 140 + .../services/flows/transports/__init__.py | 33 + .../services/flows/transports/base.py | 318 ++ .../services/flows/transports/grpc.py | 511 +++ .../services/flows/transports/grpc_asyncio.py | 515 +++ .../services/intents/__init__.py | 22 + .../services/intents/async_client.py | 580 +++ .../services/intents/client.py | 776 ++++ .../services/intents/pagers.py | 140 + .../services/intents/transports/__init__.py | 33 + .../services/intents/transports/base.py | 241 + .../services/intents/transports/grpc.py | 356 ++ .../intents/transports/grpc_asyncio.py | 360 ++ .../services/pages/__init__.py | 22 + .../services/pages/async_client.py | 631 +++ .../dialogflowcx_v3/services/pages/client.py | 863 ++++ .../dialogflowcx_v3/services/pages/pagers.py | 140 + .../services/pages/transports/__init__.py | 33 + .../services/pages/transports/base.py | 241 + .../services/pages/transports/grpc.py | 354 ++ .../services/pages/transports/grpc_asyncio.py | 358 ++ .../security_settings_service/__init__.py | 22 + .../security_settings_service/async_client.py | 586 +++ .../security_settings_service/client.py | 773 ++++ .../security_settings_service/pagers.py | 140 + .../transports/__init__.py | 33 + .../transports/base.py | 241 + .../transports/grpc.py | 359 ++ .../transports/grpc_asyncio.py | 363 ++ .../services/session_entity_types/__init__.py | 22 + .../session_entity_types/async_client.py | 632 +++ .../services/session_entity_types/client.py | 819 ++++ .../services/session_entity_types/pagers.py | 140 + .../transports/__init__.py | 33 + .../session_entity_types/transports/base.py | 241 + .../session_entity_types/transports/grpc.py | 356 ++ .../transports/grpc_asyncio.py | 360 ++ .../services/sessions/__init__.py | 22 + .../services/sessions/async_client.py | 460 ++ .../services/sessions/client.py | 703 +++ .../services/sessions/transports/__init__.py | 33 + .../services/sessions/transports/base.py | 231 + .../services/sessions/transports/grpc.py | 350 ++ .../sessions/transports/grpc_asyncio.py | 354 ++ .../services/test_cases/__init__.py | 22 + .../services/test_cases/async_client.py | 1073 +++++ .../services/test_cases/client.py | 1346 ++++++ .../services/test_cases/pagers.py | 262 ++ .../test_cases/transports/__init__.py | 33 + .../services/test_cases/transports/base.py | 346 ++ .../services/test_cases/transports/grpc.py | 562 +++ .../test_cases/transports/grpc_asyncio.py | 566 +++ .../transition_route_groups/__init__.py | 22 + .../transition_route_groups/async_client.py | 593 +++ .../transition_route_groups/client.py | 816 ++++ .../transition_route_groups/pagers.py | 140 + .../transports/__init__.py | 33 + .../transports/base.py | 241 + .../transports/grpc.py | 361 ++ .../transports/grpc_asyncio.py | 365 ++ .../services/versions/__init__.py | 22 + .../services/versions/async_client.py | 687 +++ .../services/versions/client.py | 874 ++++ .../services/versions/pagers.py | 140 + .../services/versions/transports/__init__.py | 33 + .../services/versions/transports/base.py | 262 ++ .../services/versions/transports/grpc.py | 406 ++ .../versions/transports/grpc_asyncio.py | 410 ++ .../services/webhooks/__init__.py | 22 + .../services/webhooks/async_client.py | 581 +++ .../services/webhooks/client.py | 777 ++++ .../services/webhooks/pagers.py | 140 + .../services/webhooks/transports/__init__.py | 33 + .../services/webhooks/transports/base.py | 241 + .../services/webhooks/transports/grpc.py | 356 ++ .../webhooks/transports/grpc_asyncio.py | 360 ++ .../cloud/dialogflowcx_v3/types/__init__.py | 418 ++ .../cloud/dialogflowcx_v3/types/agent.py | 491 ++ .../dialogflowcx_v3/types/audio_config.py | 356 ++ .../dialogflowcx_v3/types/entity_type.py | 425 ++ .../dialogflowcx_v3/types/environment.py | 318 ++ .../cloud/dialogflowcx_v3/types/experiment.py | 568 +++ .../cloud/dialogflowcx_v3/types/flow.py | 640 +++ .../dialogflowcx_v3/types/fulfillment.py | 182 + .../cloud/dialogflowcx_v3/types/intent.py | 474 ++ .../cloud/dialogflowcx_v3/types/page.py | 730 +++ .../dialogflowcx_v3/types/response_message.py | 340 ++ .../types/security_settings.py | 267 ++ .../cloud/dialogflowcx_v3/types/session.py | 1167 +++++ .../types/session_entity_type.py | 254 ++ .../cloud/dialogflowcx_v3/types/test_case.py | 1248 +++++ .../types/transition_route_group.py | 307 ++ .../types/validation_message.py | 113 + .../cloud/dialogflowcx_v3/types/version.py | 292 ++ .../cloud/dialogflowcx_v3/types/webhook.py | 791 ++++ owl-bot-staging/v3/mypy.ini | 3 + owl-bot-staging/v3/noxfile.py | 132 + .../scripts/fixup_dialogflowcx_v3_keywords.py | 264 ++ owl-bot-staging/v3/setup.py | 53 + owl-bot-staging/v3/tests/__init__.py | 16 + owl-bot-staging/v3/tests/unit/__init__.py | 16 + .../v3/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/dialogflowcx_v3/__init__.py | 16 + .../unit/gapic/dialogflowcx_v3/test_agents.py | 3312 ++++++++++++++ .../dialogflowcx_v3/test_entity_types.py | 2418 ++++++++++ .../dialogflowcx_v3/test_environments.py | 2851 ++++++++++++ .../gapic/dialogflowcx_v3/test_experiments.py | 2911 ++++++++++++ .../unit/gapic/dialogflowcx_v3/test_flows.py | 3472 ++++++++++++++ .../gapic/dialogflowcx_v3/test_intents.py | 2429 ++++++++++ .../unit/gapic/dialogflowcx_v3/test_pages.py | 2504 ++++++++++ .../test_security_settings_service.py | 2419 ++++++++++ .../test_session_entity_types.py | 2373 ++++++++++ .../gapic/dialogflowcx_v3/test_sessions.py | 1708 +++++++ .../gapic/dialogflowcx_v3/test_test_cases.py | 4061 +++++++++++++++++ .../test_transition_route_groups.py | 2470 ++++++++++ .../gapic/dialogflowcx_v3/test_versions.py | 2658 +++++++++++ .../gapic/dialogflowcx_v3/test_webhooks.py | 2409 ++++++++++ owl-bot-staging/v3beta1/MANIFEST.in | 2 + owl-bot-staging/v3beta1/README.rst | 49 + owl-bot-staging/v3beta1/docs/conf.py | 376 ++ .../docs/dialogflowcx_v3beta1/agents.rst | 10 + .../dialogflowcx_v3beta1/entity_types.rst | 10 + .../dialogflowcx_v3beta1/environments.rst | 10 + .../docs/dialogflowcx_v3beta1/experiments.rst | 10 + .../docs/dialogflowcx_v3beta1/flows.rst | 10 + .../docs/dialogflowcx_v3beta1/intents.rst | 10 + .../docs/dialogflowcx_v3beta1/pages.rst | 10 + .../security_settings_service.rst | 10 + .../docs/dialogflowcx_v3beta1/services.rst | 19 + .../session_entity_types.rst | 10 + .../docs/dialogflowcx_v3beta1/sessions.rst | 6 + .../docs/dialogflowcx_v3beta1/test_cases.rst | 10 + .../transition_route_groups.rst | 10 + .../docs/dialogflowcx_v3beta1/types.rst | 7 + .../docs/dialogflowcx_v3beta1/versions.rst | 10 + .../docs/dialogflowcx_v3beta1/webhooks.rst | 10 + owl-bot-staging/v3beta1/docs/index.rst | 7 + .../google/cloud/dialogflowcx/__init__.py | 451 ++ .../google/cloud/dialogflowcx/py.typed | 2 + .../cloud/dialogflowcx_v3beta1/__init__.py | 452 ++ .../dialogflowcx_v3beta1/gapic_metadata.json | 1115 +++++ .../cloud/dialogflowcx_v3beta1/py.typed | 2 + .../dialogflowcx_v3beta1/services/__init__.py | 15 + .../services/agents/__init__.py | 22 + .../services/agents/async_client.py | 894 ++++ .../services/agents/client.py | 1129 +++++ .../services/agents/pagers.py | 140 + .../services/agents/transports/__init__.py | 33 + .../services/agents/transports/base.py | 304 ++ .../services/agents/transports/grpc.py | 486 ++ .../agents/transports/grpc_asyncio.py | 490 ++ .../services/entity_types/__init__.py | 22 + .../services/entity_types/async_client.py | 659 +++ .../services/entity_types/client.py | 846 ++++ .../services/entity_types/pagers.py | 140 + .../entity_types/transports/__init__.py | 33 + .../services/entity_types/transports/base.py | 241 + .../services/entity_types/transports/grpc.py | 356 ++ .../entity_types/transports/grpc_asyncio.py | 360 ++ .../services/environments/__init__.py | 22 + .../services/environments/async_client.py | 883 ++++ .../services/environments/client.py | 1098 +++++ .../services/environments/pagers.py | 384 ++ .../environments/transports/__init__.py | 33 + .../services/environments/transports/base.py | 290 ++ .../services/environments/transports/grpc.py | 461 ++ .../environments/transports/grpc_asyncio.py | 465 ++ .../services/experiments/__init__.py | 22 + .../services/experiments/async_client.py | 740 +++ .../services/experiments/client.py | 936 ++++ .../services/experiments/pagers.py | 140 + .../experiments/transports/__init__.py | 33 + .../services/experiments/transports/base.py | 269 ++ .../services/experiments/transports/grpc.py | 420 ++ .../experiments/transports/grpc_asyncio.py | 424 ++ .../services/flows/__init__.py | 22 + .../services/flows/async_client.py | 1010 ++++ .../services/flows/client.py | 1245 +++++ .../services/flows/pagers.py | 140 + .../services/flows/transports/__init__.py | 33 + .../services/flows/transports/base.py | 318 ++ .../services/flows/transports/grpc.py | 512 +++ .../services/flows/transports/grpc_asyncio.py | 516 +++ .../services/intents/__init__.py | 22 + .../services/intents/async_client.py | 580 +++ .../services/intents/client.py | 776 ++++ .../services/intents/pagers.py | 140 + .../services/intents/transports/__init__.py | 33 + .../services/intents/transports/base.py | 241 + .../services/intents/transports/grpc.py | 356 ++ .../intents/transports/grpc_asyncio.py | 360 ++ .../services/pages/__init__.py | 22 + .../services/pages/async_client.py | 633 +++ .../services/pages/client.py | 865 ++++ .../services/pages/pagers.py | 140 + .../services/pages/transports/__init__.py | 33 + .../services/pages/transports/base.py | 241 + .../services/pages/transports/grpc.py | 355 ++ .../services/pages/transports/grpc_asyncio.py | 359 ++ .../security_settings_service/__init__.py | 22 + .../security_settings_service/async_client.py | 586 +++ .../security_settings_service/client.py | 773 ++++ .../security_settings_service/pagers.py | 140 + .../transports/__init__.py | 33 + .../transports/base.py | 241 + .../transports/grpc.py | 359 ++ .../transports/grpc_asyncio.py | 363 ++ .../services/session_entity_types/__init__.py | 22 + .../session_entity_types/async_client.py | 635 +++ .../services/session_entity_types/client.py | 822 ++++ .../services/session_entity_types/pagers.py | 140 + .../transports/__init__.py | 33 + .../session_entity_types/transports/base.py | 241 + .../session_entity_types/transports/grpc.py | 356 ++ .../transports/grpc_asyncio.py | 360 ++ .../services/sessions/__init__.py | 22 + .../services/sessions/async_client.py | 460 ++ .../services/sessions/client.py | 703 +++ .../services/sessions/transports/__init__.py | 33 + .../services/sessions/transports/base.py | 231 + .../services/sessions/transports/grpc.py | 350 ++ .../sessions/transports/grpc_asyncio.py | 354 ++ .../services/test_cases/__init__.py | 22 + .../services/test_cases/async_client.py | 1073 +++++ .../services/test_cases/client.py | 1346 ++++++ .../services/test_cases/pagers.py | 262 ++ .../test_cases/transports/__init__.py | 33 + .../services/test_cases/transports/base.py | 346 ++ .../services/test_cases/transports/grpc.py | 562 +++ .../test_cases/transports/grpc_asyncio.py | 566 +++ .../transition_route_groups/__init__.py | 22 + .../transition_route_groups/async_client.py | 593 +++ .../transition_route_groups/client.py | 816 ++++ .../transition_route_groups/pagers.py | 140 + .../transports/__init__.py | 33 + .../transports/base.py | 241 + .../transports/grpc.py | 361 ++ .../transports/grpc_asyncio.py | 365 ++ .../services/versions/__init__.py | 22 + .../services/versions/async_client.py | 690 +++ .../services/versions/client.py | 877 ++++ .../services/versions/pagers.py | 140 + .../services/versions/transports/__init__.py | 33 + .../services/versions/transports/base.py | 262 ++ .../services/versions/transports/grpc.py | 407 ++ .../versions/transports/grpc_asyncio.py | 411 ++ .../services/webhooks/__init__.py | 22 + .../services/webhooks/async_client.py | 581 +++ .../services/webhooks/client.py | 777 ++++ .../services/webhooks/pagers.py | 140 + .../services/webhooks/transports/__init__.py | 33 + .../services/webhooks/transports/base.py | 241 + .../services/webhooks/transports/grpc.py | 356 ++ .../webhooks/transports/grpc_asyncio.py | 360 ++ .../dialogflowcx_v3beta1/types/__init__.py | 430 ++ .../cloud/dialogflowcx_v3beta1/types/agent.py | 491 ++ .../types/audio_config.py | 357 ++ .../dialogflowcx_v3beta1/types/entity_type.py | 425 ++ .../dialogflowcx_v3beta1/types/environment.py | 478 ++ .../dialogflowcx_v3beta1/types/experiment.py | 570 +++ .../cloud/dialogflowcx_v3beta1/types/flow.py | 640 +++ .../dialogflowcx_v3beta1/types/fulfillment.py | 182 + .../dialogflowcx_v3beta1/types/intent.py | 474 ++ .../cloud/dialogflowcx_v3beta1/types/page.py | 730 +++ .../types/response_message.py | 340 ++ .../types/security_settings.py | 267 ++ .../dialogflowcx_v3beta1/types/session.py | 1172 +++++ .../types/session_entity_type.py | 254 ++ .../dialogflowcx_v3beta1/types/test_case.py | 1250 +++++ .../types/transition_route_group.py | 307 ++ .../types/validation_message.py | 113 + .../dialogflowcx_v3beta1/types/version.py | 295 ++ .../dialogflowcx_v3beta1/types/webhook.py | 793 ++++ owl-bot-staging/v3beta1/mypy.ini | 3 + owl-bot-staging/v3beta1/noxfile.py | 132 + .../fixup_dialogflowcx_v3beta1_keywords.py | 266 ++ owl-bot-staging/v3beta1/setup.py | 53 + owl-bot-staging/v3beta1/tests/__init__.py | 16 + .../v3beta1/tests/unit/__init__.py | 16 + .../v3beta1/tests/unit/gapic/__init__.py | 16 + .../gapic/dialogflowcx_v3beta1/__init__.py | 16 + .../gapic/dialogflowcx_v3beta1/test_agents.py | 3312 ++++++++++++++ .../dialogflowcx_v3beta1/test_entity_types.py | 2418 ++++++++++ .../dialogflowcx_v3beta1/test_environments.py | 3467 ++++++++++++++ .../dialogflowcx_v3beta1/test_experiments.py | 2911 ++++++++++++ .../gapic/dialogflowcx_v3beta1/test_flows.py | 3472 ++++++++++++++ .../dialogflowcx_v3beta1/test_intents.py | 2429 ++++++++++ .../gapic/dialogflowcx_v3beta1/test_pages.py | 2504 ++++++++++ .../test_security_settings_service.py | 2419 ++++++++++ .../test_session_entity_types.py | 2373 ++++++++++ .../dialogflowcx_v3beta1/test_sessions.py | 1708 +++++++ .../dialogflowcx_v3beta1/test_test_cases.py | 4061 +++++++++++++++++ .../test_transition_route_groups.py | 2470 ++++++++++ .../dialogflowcx_v3beta1/test_versions.py | 2658 +++++++++++ .../dialogflowcx_v3beta1/test_webhooks.py | 2409 ++++++++++ 356 files changed, 183452 insertions(+) create mode 100644 owl-bot-staging/v3/MANIFEST.in create mode 100644 owl-bot-staging/v3/README.rst create mode 100644 owl-bot-staging/v3/docs/conf.py create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/agents.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst create mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst create mode 100644 owl-bot-staging/v3/docs/index.rst create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session_entity_type.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/test_case.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/transition_route_group.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/validation_message.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/version.py create mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/webhook.py create mode 100644 owl-bot-staging/v3/mypy.ini create mode 100644 owl-bot-staging/v3/noxfile.py create mode 100644 owl-bot-staging/v3/scripts/fixup_dialogflowcx_v3_keywords.py create mode 100644 owl-bot-staging/v3/setup.py create mode 100644 owl-bot-staging/v3/tests/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/__init__.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_agents.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_environments.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_experiments.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_flows.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_intents.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_pages.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_sessions.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_versions.py create mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py create mode 100644 owl-bot-staging/v3beta1/MANIFEST.in create mode 100644 owl-bot-staging/v3beta1/README.rst create mode 100644 owl-bot-staging/v3beta1/docs/conf.py create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/agents.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/entity_types.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/environments.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/experiments.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/flows.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/intents.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/pages.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/security_settings_service.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/services.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/session_entity_types.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/sessions.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/test_cases.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/transition_route_groups.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/types.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/versions.rst create mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/webhooks.rst create mode 100644 owl-bot-staging/v3beta1/docs/index.rst create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx/py.typed create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/py.typed create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/__init__.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/agent.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/audio_config.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/entity_type.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/environment.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/experiment.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/flow.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/intent.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/page.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/response_message.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/security_settings.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/test_case.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/validation_message.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/version.py create mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/webhook.py create mode 100644 owl-bot-staging/v3beta1/mypy.ini create mode 100644 owl-bot-staging/v3beta1/noxfile.py create mode 100644 owl-bot-staging/v3beta1/scripts/fixup_dialogflowcx_v3beta1_keywords.py create mode 100644 owl-bot-staging/v3beta1/setup.py create mode 100644 owl-bot-staging/v3beta1/tests/__init__.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py create mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py diff --git a/owl-bot-staging/v3/MANIFEST.in b/owl-bot-staging/v3/MANIFEST.in new file mode 100644 index 00000000..83900298 --- /dev/null +++ b/owl-bot-staging/v3/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/dialogflowcx *.py +recursive-include google/cloud/dialogflowcx_v3 *.py diff --git a/owl-bot-staging/v3/README.rst b/owl-bot-staging/v3/README.rst new file mode 100644 index 00000000..bfe57a44 --- /dev/null +++ b/owl-bot-staging/v3/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Dialogflowcx 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 Dialogflowcx 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/v3/docs/conf.py b/owl-bot-staging/v3/docs/conf.py new file mode 100644 index 00000000..814121cd --- /dev/null +++ b/owl-bot-staging/v3/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-dialogflowcx 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-dialogflowcx" +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-dialogflowcx-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-dialogflowcx.tex", + u"google-cloud-dialogflowcx 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-dialogflowcx", + u"Google Cloud Dialogflowcx 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-dialogflowcx", + u"google-cloud-dialogflowcx Documentation", + author, + "google-cloud-dialogflowcx", + "GAPIC library for Google Cloud Dialogflowcx 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/v3/docs/dialogflowcx_v3/agents.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/agents.rst new file mode 100644 index 00000000..4deb1730 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/agents.rst @@ -0,0 +1,10 @@ +Agents +------------------------ + +.. automodule:: google.cloud.dialogflowcx_v3.services.agents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.agents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst new file mode 100644 index 00000000..08e4b6e8 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst @@ -0,0 +1,10 @@ +EntityTypes +----------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.entity_types + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.entity_types.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst new file mode 100644 index 00000000..246ee15a --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst @@ -0,0 +1,10 @@ +Environments +------------------------------ + +.. automodule:: google.cloud.dialogflowcx_v3.services.environments + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.environments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst new file mode 100644 index 00000000..5cba0e2a --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst @@ -0,0 +1,10 @@ +Experiments +----------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.experiments + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.experiments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst new file mode 100644 index 00000000..77f6398e --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst @@ -0,0 +1,10 @@ +Flows +----------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.flows + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.flows.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst new file mode 100644 index 00000000..8b9e6dda --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst @@ -0,0 +1,10 @@ +Intents +------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.intents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.intents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst new file mode 100644 index 00000000..0bbfbced --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst @@ -0,0 +1,10 @@ +Pages +----------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.pages + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.pages.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst new file mode 100644 index 00000000..4b4fa007 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst @@ -0,0 +1,10 @@ +SecuritySettingsService +----------------------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.security_settings_service + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.security_settings_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst new file mode 100644 index 00000000..3da663c9 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst @@ -0,0 +1,19 @@ +Services for Google Cloud Dialogflowcx v3 API +============================================= +.. toctree:: + :maxdepth: 2 + + agents + entity_types + environments + experiments + flows + intents + pages + security_settings_service + session_entity_types + sessions + test_cases + transition_route_groups + versions + webhooks diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst new file mode 100644 index 00000000..46ff0f6e --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst @@ -0,0 +1,10 @@ +SessionEntityTypes +------------------------------------ + +.. automodule:: google.cloud.dialogflowcx_v3.services.session_entity_types + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.session_entity_types.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst new file mode 100644 index 00000000..494bceb1 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst @@ -0,0 +1,6 @@ +Sessions +-------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.sessions + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst new file mode 100644 index 00000000..3cad4dd4 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst @@ -0,0 +1,10 @@ +TestCases +--------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.test_cases + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.test_cases.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst new file mode 100644 index 00000000..d5549da9 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst @@ -0,0 +1,10 @@ +TransitionRouteGroups +--------------------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.transition_route_groups + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.transition_route_groups.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst new file mode 100644 index 00000000..7e2b1c53 --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Dialogflowcx v3 API +========================================== + +.. automodule:: google.cloud.dialogflowcx_v3.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst new file mode 100644 index 00000000..2d72f02d --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst @@ -0,0 +1,10 @@ +Versions +-------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.versions + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.versions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst new file mode 100644 index 00000000..2e2f9b8c --- /dev/null +++ b/owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst @@ -0,0 +1,10 @@ +Webhooks +-------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3.services.webhooks + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3.services.webhooks.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3/docs/index.rst b/owl-bot-staging/v3/docs/index.rst new file mode 100644 index 00000000..eaab73b8 --- /dev/null +++ b/owl-bot-staging/v3/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + dialogflowcx_v3/services + dialogflowcx_v3/types diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py new file mode 100644 index 00000000..9e9c5117 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py @@ -0,0 +1,439 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.agents.client import AgentsClient +from google.cloud.dialogflowcx_v3.services.agents.async_client import AgentsAsyncClient +from google.cloud.dialogflowcx_v3.services.entity_types.client import EntityTypesClient +from google.cloud.dialogflowcx_v3.services.entity_types.async_client import EntityTypesAsyncClient +from google.cloud.dialogflowcx_v3.services.environments.client import EnvironmentsClient +from google.cloud.dialogflowcx_v3.services.environments.async_client import EnvironmentsAsyncClient +from google.cloud.dialogflowcx_v3.services.experiments.client import ExperimentsClient +from google.cloud.dialogflowcx_v3.services.experiments.async_client import ExperimentsAsyncClient +from google.cloud.dialogflowcx_v3.services.flows.client import FlowsClient +from google.cloud.dialogflowcx_v3.services.flows.async_client import FlowsAsyncClient +from google.cloud.dialogflowcx_v3.services.intents.client import IntentsClient +from google.cloud.dialogflowcx_v3.services.intents.async_client import IntentsAsyncClient +from google.cloud.dialogflowcx_v3.services.pages.client import PagesClient +from google.cloud.dialogflowcx_v3.services.pages.async_client import PagesAsyncClient +from google.cloud.dialogflowcx_v3.services.security_settings_service.client import SecuritySettingsServiceClient +from google.cloud.dialogflowcx_v3.services.security_settings_service.async_client import SecuritySettingsServiceAsyncClient +from google.cloud.dialogflowcx_v3.services.session_entity_types.client import SessionEntityTypesClient +from google.cloud.dialogflowcx_v3.services.session_entity_types.async_client import SessionEntityTypesAsyncClient +from google.cloud.dialogflowcx_v3.services.sessions.client import SessionsClient +from google.cloud.dialogflowcx_v3.services.sessions.async_client import SessionsAsyncClient +from google.cloud.dialogflowcx_v3.services.test_cases.client import TestCasesClient +from google.cloud.dialogflowcx_v3.services.test_cases.async_client import TestCasesAsyncClient +from google.cloud.dialogflowcx_v3.services.transition_route_groups.client import TransitionRouteGroupsClient +from google.cloud.dialogflowcx_v3.services.transition_route_groups.async_client import TransitionRouteGroupsAsyncClient +from google.cloud.dialogflowcx_v3.services.versions.client import VersionsClient +from google.cloud.dialogflowcx_v3.services.versions.async_client import VersionsAsyncClient +from google.cloud.dialogflowcx_v3.services.webhooks.client import WebhooksClient +from google.cloud.dialogflowcx_v3.services.webhooks.async_client import WebhooksAsyncClient + +from google.cloud.dialogflowcx_v3.types.agent import Agent +from google.cloud.dialogflowcx_v3.types.agent import AgentValidationResult +from google.cloud.dialogflowcx_v3.types.agent import CreateAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import DeleteAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import ExportAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import ExportAgentResponse +from google.cloud.dialogflowcx_v3.types.agent import GetAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import GetAgentValidationResultRequest +from google.cloud.dialogflowcx_v3.types.agent import ListAgentsRequest +from google.cloud.dialogflowcx_v3.types.agent import ListAgentsResponse +from google.cloud.dialogflowcx_v3.types.agent import RestoreAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import SpeechToTextSettings +from google.cloud.dialogflowcx_v3.types.agent import UpdateAgentRequest +from google.cloud.dialogflowcx_v3.types.agent import ValidateAgentRequest +from google.cloud.dialogflowcx_v3.types.audio_config import InputAudioConfig +from google.cloud.dialogflowcx_v3.types.audio_config import OutputAudioConfig +from google.cloud.dialogflowcx_v3.types.audio_config import SpeechWordInfo +from google.cloud.dialogflowcx_v3.types.audio_config import SynthesizeSpeechConfig +from google.cloud.dialogflowcx_v3.types.audio_config import VoiceSelectionParams +from google.cloud.dialogflowcx_v3.types.audio_config import AudioEncoding +from google.cloud.dialogflowcx_v3.types.audio_config import OutputAudioEncoding +from google.cloud.dialogflowcx_v3.types.audio_config import SpeechModelVariant +from google.cloud.dialogflowcx_v3.types.audio_config import SsmlVoiceGender +from google.cloud.dialogflowcx_v3.types.entity_type import CreateEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.entity_type import DeleteEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.entity_type import EntityType +from google.cloud.dialogflowcx_v3.types.entity_type import GetEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.entity_type import ListEntityTypesRequest +from google.cloud.dialogflowcx_v3.types.entity_type import ListEntityTypesResponse +from google.cloud.dialogflowcx_v3.types.entity_type import UpdateEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.environment import CreateEnvironmentRequest +from google.cloud.dialogflowcx_v3.types.environment import DeleteEnvironmentRequest +from google.cloud.dialogflowcx_v3.types.environment import Environment +from google.cloud.dialogflowcx_v3.types.environment import GetEnvironmentRequest +from google.cloud.dialogflowcx_v3.types.environment import ListEnvironmentsRequest +from google.cloud.dialogflowcx_v3.types.environment import ListEnvironmentsResponse +from google.cloud.dialogflowcx_v3.types.environment import LookupEnvironmentHistoryRequest +from google.cloud.dialogflowcx_v3.types.environment import LookupEnvironmentHistoryResponse +from google.cloud.dialogflowcx_v3.types.environment import UpdateEnvironmentRequest +from google.cloud.dialogflowcx_v3.types.experiment import CreateExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import DeleteExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import Experiment +from google.cloud.dialogflowcx_v3.types.experiment import GetExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import ListExperimentsRequest +from google.cloud.dialogflowcx_v3.types.experiment import ListExperimentsResponse +from google.cloud.dialogflowcx_v3.types.experiment import StartExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import StopExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import UpdateExperimentRequest +from google.cloud.dialogflowcx_v3.types.experiment import VariantsHistory +from google.cloud.dialogflowcx_v3.types.experiment import VersionVariants +from google.cloud.dialogflowcx_v3.types.flow import CreateFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import DeleteFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ExportFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ExportFlowResponse +from google.cloud.dialogflowcx_v3.types.flow import Flow +from google.cloud.dialogflowcx_v3.types.flow import FlowValidationResult +from google.cloud.dialogflowcx_v3.types.flow import GetFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import GetFlowValidationResultRequest +from google.cloud.dialogflowcx_v3.types.flow import ImportFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ImportFlowResponse +from google.cloud.dialogflowcx_v3.types.flow import ListFlowsRequest +from google.cloud.dialogflowcx_v3.types.flow import ListFlowsResponse +from google.cloud.dialogflowcx_v3.types.flow import NluSettings +from google.cloud.dialogflowcx_v3.types.flow import TrainFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import UpdateFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ValidateFlowRequest +from google.cloud.dialogflowcx_v3.types.fulfillment import Fulfillment +from google.cloud.dialogflowcx_v3.types.intent import CreateIntentRequest +from google.cloud.dialogflowcx_v3.types.intent import DeleteIntentRequest +from google.cloud.dialogflowcx_v3.types.intent import GetIntentRequest +from google.cloud.dialogflowcx_v3.types.intent import Intent +from google.cloud.dialogflowcx_v3.types.intent import ListIntentsRequest +from google.cloud.dialogflowcx_v3.types.intent import ListIntentsResponse +from google.cloud.dialogflowcx_v3.types.intent import UpdateIntentRequest +from google.cloud.dialogflowcx_v3.types.intent import IntentView +from google.cloud.dialogflowcx_v3.types.page import CreatePageRequest +from google.cloud.dialogflowcx_v3.types.page import DeletePageRequest +from google.cloud.dialogflowcx_v3.types.page import EventHandler +from google.cloud.dialogflowcx_v3.types.page import Form +from google.cloud.dialogflowcx_v3.types.page import GetPageRequest +from google.cloud.dialogflowcx_v3.types.page import ListPagesRequest +from google.cloud.dialogflowcx_v3.types.page import ListPagesResponse +from google.cloud.dialogflowcx_v3.types.page import Page +from google.cloud.dialogflowcx_v3.types.page import TransitionRoute +from google.cloud.dialogflowcx_v3.types.page import UpdatePageRequest +from google.cloud.dialogflowcx_v3.types.response_message import ResponseMessage +from google.cloud.dialogflowcx_v3.types.security_settings import CreateSecuritySettingsRequest +from google.cloud.dialogflowcx_v3.types.security_settings import DeleteSecuritySettingsRequest +from google.cloud.dialogflowcx_v3.types.security_settings import GetSecuritySettingsRequest +from google.cloud.dialogflowcx_v3.types.security_settings import ListSecuritySettingsRequest +from google.cloud.dialogflowcx_v3.types.security_settings import ListSecuritySettingsResponse +from google.cloud.dialogflowcx_v3.types.security_settings import SecuritySettings +from google.cloud.dialogflowcx_v3.types.security_settings import UpdateSecuritySettingsRequest +from google.cloud.dialogflowcx_v3.types.session import AudioInput +from google.cloud.dialogflowcx_v3.types.session import DetectIntentRequest +from google.cloud.dialogflowcx_v3.types.session import DetectIntentResponse +from google.cloud.dialogflowcx_v3.types.session import DtmfInput +from google.cloud.dialogflowcx_v3.types.session import EventInput +from google.cloud.dialogflowcx_v3.types.session import FulfillIntentRequest +from google.cloud.dialogflowcx_v3.types.session import FulfillIntentResponse +from google.cloud.dialogflowcx_v3.types.session import IntentInput +from google.cloud.dialogflowcx_v3.types.session import Match +from google.cloud.dialogflowcx_v3.types.session import MatchIntentRequest +from google.cloud.dialogflowcx_v3.types.session import MatchIntentResponse +from google.cloud.dialogflowcx_v3.types.session import QueryInput +from google.cloud.dialogflowcx_v3.types.session import QueryParameters +from google.cloud.dialogflowcx_v3.types.session import QueryResult +from google.cloud.dialogflowcx_v3.types.session import SentimentAnalysisResult +from google.cloud.dialogflowcx_v3.types.session import StreamingDetectIntentRequest +from google.cloud.dialogflowcx_v3.types.session import StreamingDetectIntentResponse +from google.cloud.dialogflowcx_v3.types.session import StreamingRecognitionResult +from google.cloud.dialogflowcx_v3.types.session import TextInput +from google.cloud.dialogflowcx_v3.types.session_entity_type import CreateSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.session_entity_type import DeleteSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.session_entity_type import GetSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.session_entity_type import ListSessionEntityTypesRequest +from google.cloud.dialogflowcx_v3.types.session_entity_type import ListSessionEntityTypesResponse +from google.cloud.dialogflowcx_v3.types.session_entity_type import SessionEntityType +from google.cloud.dialogflowcx_v3.types.session_entity_type import UpdateSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3.types.test_case import BatchDeleteTestCasesRequest +from google.cloud.dialogflowcx_v3.types.test_case import BatchRunTestCasesMetadata +from google.cloud.dialogflowcx_v3.types.test_case import BatchRunTestCasesRequest +from google.cloud.dialogflowcx_v3.types.test_case import BatchRunTestCasesResponse +from google.cloud.dialogflowcx_v3.types.test_case import CalculateCoverageRequest +from google.cloud.dialogflowcx_v3.types.test_case import CalculateCoverageResponse +from google.cloud.dialogflowcx_v3.types.test_case import ConversationTurn +from google.cloud.dialogflowcx_v3.types.test_case import CreateTestCaseRequest +from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesMetadata +from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesRequest +from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesResponse +from google.cloud.dialogflowcx_v3.types.test_case import GetTestCaseRequest +from google.cloud.dialogflowcx_v3.types.test_case import GetTestCaseResultRequest +from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesMetadata +from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesRequest +from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesResponse +from google.cloud.dialogflowcx_v3.types.test_case import IntentCoverage +from google.cloud.dialogflowcx_v3.types.test_case import ListTestCaseResultsRequest +from google.cloud.dialogflowcx_v3.types.test_case import ListTestCaseResultsResponse +from google.cloud.dialogflowcx_v3.types.test_case import ListTestCasesRequest +from google.cloud.dialogflowcx_v3.types.test_case import ListTestCasesResponse +from google.cloud.dialogflowcx_v3.types.test_case import RunTestCaseMetadata +from google.cloud.dialogflowcx_v3.types.test_case import RunTestCaseRequest +from google.cloud.dialogflowcx_v3.types.test_case import RunTestCaseResponse +from google.cloud.dialogflowcx_v3.types.test_case import TestCase +from google.cloud.dialogflowcx_v3.types.test_case import TestCaseError +from google.cloud.dialogflowcx_v3.types.test_case import TestCaseResult +from google.cloud.dialogflowcx_v3.types.test_case import TestConfig +from google.cloud.dialogflowcx_v3.types.test_case import TestError +from google.cloud.dialogflowcx_v3.types.test_case import TestRunDifference +from google.cloud.dialogflowcx_v3.types.test_case import TransitionCoverage +from google.cloud.dialogflowcx_v3.types.test_case import TransitionRouteGroupCoverage +from google.cloud.dialogflowcx_v3.types.test_case import UpdateTestCaseRequest +from google.cloud.dialogflowcx_v3.types.test_case import TestResult +from google.cloud.dialogflowcx_v3.types.transition_route_group import CreateTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3.types.transition_route_group import DeleteTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3.types.transition_route_group import GetTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3.types.transition_route_group import ListTransitionRouteGroupsRequest +from google.cloud.dialogflowcx_v3.types.transition_route_group import ListTransitionRouteGroupsResponse +from google.cloud.dialogflowcx_v3.types.transition_route_group import TransitionRouteGroup +from google.cloud.dialogflowcx_v3.types.transition_route_group import UpdateTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3.types.validation_message import ResourceName +from google.cloud.dialogflowcx_v3.types.validation_message import ValidationMessage +from google.cloud.dialogflowcx_v3.types.version import CreateVersionOperationMetadata +from google.cloud.dialogflowcx_v3.types.version import CreateVersionRequest +from google.cloud.dialogflowcx_v3.types.version import DeleteVersionRequest +from google.cloud.dialogflowcx_v3.types.version import GetVersionRequest +from google.cloud.dialogflowcx_v3.types.version import ListVersionsRequest +from google.cloud.dialogflowcx_v3.types.version import ListVersionsResponse +from google.cloud.dialogflowcx_v3.types.version import LoadVersionRequest +from google.cloud.dialogflowcx_v3.types.version import UpdateVersionRequest +from google.cloud.dialogflowcx_v3.types.version import Version +from google.cloud.dialogflowcx_v3.types.webhook import CreateWebhookRequest +from google.cloud.dialogflowcx_v3.types.webhook import DeleteWebhookRequest +from google.cloud.dialogflowcx_v3.types.webhook import GetWebhookRequest +from google.cloud.dialogflowcx_v3.types.webhook import ListWebhooksRequest +from google.cloud.dialogflowcx_v3.types.webhook import ListWebhooksResponse +from google.cloud.dialogflowcx_v3.types.webhook import PageInfo +from google.cloud.dialogflowcx_v3.types.webhook import SessionInfo +from google.cloud.dialogflowcx_v3.types.webhook import UpdateWebhookRequest +from google.cloud.dialogflowcx_v3.types.webhook import Webhook +from google.cloud.dialogflowcx_v3.types.webhook import WebhookRequest +from google.cloud.dialogflowcx_v3.types.webhook import WebhookResponse + +__all__ = ('AgentsClient', + 'AgentsAsyncClient', + 'EntityTypesClient', + 'EntityTypesAsyncClient', + 'EnvironmentsClient', + 'EnvironmentsAsyncClient', + 'ExperimentsClient', + 'ExperimentsAsyncClient', + 'FlowsClient', + 'FlowsAsyncClient', + 'IntentsClient', + 'IntentsAsyncClient', + 'PagesClient', + 'PagesAsyncClient', + 'SecuritySettingsServiceClient', + 'SecuritySettingsServiceAsyncClient', + 'SessionEntityTypesClient', + 'SessionEntityTypesAsyncClient', + 'SessionsClient', + 'SessionsAsyncClient', + 'TestCasesClient', + 'TestCasesAsyncClient', + 'TransitionRouteGroupsClient', + 'TransitionRouteGroupsAsyncClient', + 'VersionsClient', + 'VersionsAsyncClient', + 'WebhooksClient', + 'WebhooksAsyncClient', + 'Agent', + 'AgentValidationResult', + 'CreateAgentRequest', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'GetAgentRequest', + 'GetAgentValidationResultRequest', + 'ListAgentsRequest', + 'ListAgentsResponse', + 'RestoreAgentRequest', + 'SpeechToTextSettings', + 'UpdateAgentRequest', + 'ValidateAgentRequest', + 'InputAudioConfig', + 'OutputAudioConfig', + 'SpeechWordInfo', + 'SynthesizeSpeechConfig', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'Environment', + 'GetEnvironmentRequest', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LookupEnvironmentHistoryRequest', + 'LookupEnvironmentHistoryResponse', + 'UpdateEnvironmentRequest', + 'CreateExperimentRequest', + 'DeleteExperimentRequest', + 'Experiment', + 'GetExperimentRequest', + 'ListExperimentsRequest', + 'ListExperimentsResponse', + 'StartExperimentRequest', + 'StopExperimentRequest', + 'UpdateExperimentRequest', + 'VariantsHistory', + 'VersionVariants', + 'CreateFlowRequest', + 'DeleteFlowRequest', + 'ExportFlowRequest', + 'ExportFlowResponse', + 'Flow', + 'FlowValidationResult', + 'GetFlowRequest', + 'GetFlowValidationResultRequest', + 'ImportFlowRequest', + 'ImportFlowResponse', + 'ListFlowsRequest', + 'ListFlowsResponse', + 'NluSettings', + 'TrainFlowRequest', + 'UpdateFlowRequest', + 'ValidateFlowRequest', + 'Fulfillment', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreatePageRequest', + 'DeletePageRequest', + 'EventHandler', + 'Form', + 'GetPageRequest', + 'ListPagesRequest', + 'ListPagesResponse', + 'Page', + 'TransitionRoute', + 'UpdatePageRequest', + 'ResponseMessage', + 'CreateSecuritySettingsRequest', + 'DeleteSecuritySettingsRequest', + 'GetSecuritySettingsRequest', + 'ListSecuritySettingsRequest', + 'ListSecuritySettingsResponse', + 'SecuritySettings', + 'UpdateSecuritySettingsRequest', + 'AudioInput', + 'DetectIntentRequest', + 'DetectIntentResponse', + 'DtmfInput', + 'EventInput', + 'FulfillIntentRequest', + 'FulfillIntentResponse', + 'IntentInput', + 'Match', + 'MatchIntentRequest', + 'MatchIntentResponse', + 'QueryInput', + 'QueryParameters', + 'QueryResult', + 'SentimentAnalysisResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'CreateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + 'GetSessionEntityTypeRequest', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'SessionEntityType', + 'UpdateSessionEntityTypeRequest', + 'BatchDeleteTestCasesRequest', + 'BatchRunTestCasesMetadata', + 'BatchRunTestCasesRequest', + 'BatchRunTestCasesResponse', + 'CalculateCoverageRequest', + 'CalculateCoverageResponse', + 'ConversationTurn', + 'CreateTestCaseRequest', + 'ExportTestCasesMetadata', + 'ExportTestCasesRequest', + 'ExportTestCasesResponse', + 'GetTestCaseRequest', + 'GetTestCaseResultRequest', + 'ImportTestCasesMetadata', + 'ImportTestCasesRequest', + 'ImportTestCasesResponse', + 'IntentCoverage', + 'ListTestCaseResultsRequest', + 'ListTestCaseResultsResponse', + 'ListTestCasesRequest', + 'ListTestCasesResponse', + 'RunTestCaseMetadata', + 'RunTestCaseRequest', + 'RunTestCaseResponse', + 'TestCase', + 'TestCaseError', + 'TestCaseResult', + 'TestConfig', + 'TestError', + 'TestRunDifference', + 'TransitionCoverage', + 'TransitionRouteGroupCoverage', + 'UpdateTestCaseRequest', + 'TestResult', + 'CreateTransitionRouteGroupRequest', + 'DeleteTransitionRouteGroupRequest', + 'GetTransitionRouteGroupRequest', + 'ListTransitionRouteGroupsRequest', + 'ListTransitionRouteGroupsResponse', + 'TransitionRouteGroup', + 'UpdateTransitionRouteGroupRequest', + 'ResourceName', + 'ValidationMessage', + 'CreateVersionOperationMetadata', + 'CreateVersionRequest', + 'DeleteVersionRequest', + 'GetVersionRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'LoadVersionRequest', + 'UpdateVersionRequest', + 'Version', + 'CreateWebhookRequest', + 'DeleteWebhookRequest', + 'GetWebhookRequest', + 'ListWebhooksRequest', + 'ListWebhooksResponse', + 'PageInfo', + 'SessionInfo', + 'UpdateWebhookRequest', + 'Webhook', + 'WebhookRequest', + 'WebhookResponse', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed b/owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed new file mode 100644 index 00000000..60fdca49 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dialogflowcx package uses inline types. diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py new file mode 100644 index 00000000..50d0af79 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py @@ -0,0 +1,440 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient +from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.experiments import ExperimentsClient +from .services.experiments import ExperimentsAsyncClient +from .services.flows import FlowsClient +from .services.flows import FlowsAsyncClient +from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient +from .services.pages import PagesClient +from .services.pages import PagesAsyncClient +from .services.security_settings_service import SecuritySettingsServiceClient +from .services.security_settings_service import SecuritySettingsServiceAsyncClient +from .services.session_entity_types import SessionEntityTypesClient +from .services.session_entity_types import SessionEntityTypesAsyncClient +from .services.sessions import SessionsClient +from .services.sessions import SessionsAsyncClient +from .services.test_cases import TestCasesClient +from .services.test_cases import TestCasesAsyncClient +from .services.transition_route_groups import TransitionRouteGroupsClient +from .services.transition_route_groups import TransitionRouteGroupsAsyncClient +from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient +from .services.webhooks import WebhooksClient +from .services.webhooks import WebhooksAsyncClient + +from .types.agent import Agent +from .types.agent import AgentValidationResult +from .types.agent import CreateAgentRequest +from .types.agent import DeleteAgentRequest +from .types.agent import ExportAgentRequest +from .types.agent import ExportAgentResponse +from .types.agent import GetAgentRequest +from .types.agent import GetAgentValidationResultRequest +from .types.agent import ListAgentsRequest +from .types.agent import ListAgentsResponse +from .types.agent import RestoreAgentRequest +from .types.agent import SpeechToTextSettings +from .types.agent import UpdateAgentRequest +from .types.agent import ValidateAgentRequest +from .types.audio_config import InputAudioConfig +from .types.audio_config import OutputAudioConfig +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.entity_type import CreateEntityTypeRequest +from .types.entity_type import DeleteEntityTypeRequest +from .types.entity_type import EntityType +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 GetEnvironmentRequest +from .types.environment import ListEnvironmentsRequest +from .types.environment import ListEnvironmentsResponse +from .types.environment import LookupEnvironmentHistoryRequest +from .types.environment import LookupEnvironmentHistoryResponse +from .types.environment import UpdateEnvironmentRequest +from .types.experiment import CreateExperimentRequest +from .types.experiment import DeleteExperimentRequest +from .types.experiment import Experiment +from .types.experiment import GetExperimentRequest +from .types.experiment import ListExperimentsRequest +from .types.experiment import ListExperimentsResponse +from .types.experiment import StartExperimentRequest +from .types.experiment import StopExperimentRequest +from .types.experiment import UpdateExperimentRequest +from .types.experiment import VariantsHistory +from .types.experiment import VersionVariants +from .types.flow import CreateFlowRequest +from .types.flow import DeleteFlowRequest +from .types.flow import ExportFlowRequest +from .types.flow import ExportFlowResponse +from .types.flow import Flow +from .types.flow import FlowValidationResult +from .types.flow import GetFlowRequest +from .types.flow import GetFlowValidationResultRequest +from .types.flow import ImportFlowRequest +from .types.flow import ImportFlowResponse +from .types.flow import ListFlowsRequest +from .types.flow import ListFlowsResponse +from .types.flow import NluSettings +from .types.flow import TrainFlowRequest +from .types.flow import UpdateFlowRequest +from .types.flow import ValidateFlowRequest +from .types.fulfillment import Fulfillment +from .types.intent import CreateIntentRequest +from .types.intent import DeleteIntentRequest +from .types.intent import GetIntentRequest +from .types.intent import Intent +from .types.intent import ListIntentsRequest +from .types.intent import ListIntentsResponse +from .types.intent import UpdateIntentRequest +from .types.intent import IntentView +from .types.page import CreatePageRequest +from .types.page import DeletePageRequest +from .types.page import EventHandler +from .types.page import Form +from .types.page import GetPageRequest +from .types.page import ListPagesRequest +from .types.page import ListPagesResponse +from .types.page import Page +from .types.page import TransitionRoute +from .types.page import UpdatePageRequest +from .types.response_message import ResponseMessage +from .types.security_settings import CreateSecuritySettingsRequest +from .types.security_settings import DeleteSecuritySettingsRequest +from .types.security_settings import GetSecuritySettingsRequest +from .types.security_settings import ListSecuritySettingsRequest +from .types.security_settings import ListSecuritySettingsResponse +from .types.security_settings import SecuritySettings +from .types.security_settings import UpdateSecuritySettingsRequest +from .types.session import AudioInput +from .types.session import DetectIntentRequest +from .types.session import DetectIntentResponse +from .types.session import DtmfInput +from .types.session import EventInput +from .types.session import FulfillIntentRequest +from .types.session import FulfillIntentResponse +from .types.session import IntentInput +from .types.session import Match +from .types.session import MatchIntentRequest +from .types.session import MatchIntentResponse +from .types.session import QueryInput +from .types.session import QueryParameters +from .types.session import QueryResult +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.test_case import BatchDeleteTestCasesRequest +from .types.test_case import BatchRunTestCasesMetadata +from .types.test_case import BatchRunTestCasesRequest +from .types.test_case import BatchRunTestCasesResponse +from .types.test_case import CalculateCoverageRequest +from .types.test_case import CalculateCoverageResponse +from .types.test_case import ConversationTurn +from .types.test_case import CreateTestCaseRequest +from .types.test_case import ExportTestCasesMetadata +from .types.test_case import ExportTestCasesRequest +from .types.test_case import ExportTestCasesResponse +from .types.test_case import GetTestCaseRequest +from .types.test_case import GetTestCaseResultRequest +from .types.test_case import ImportTestCasesMetadata +from .types.test_case import ImportTestCasesRequest +from .types.test_case import ImportTestCasesResponse +from .types.test_case import IntentCoverage +from .types.test_case import ListTestCaseResultsRequest +from .types.test_case import ListTestCaseResultsResponse +from .types.test_case import ListTestCasesRequest +from .types.test_case import ListTestCasesResponse +from .types.test_case import RunTestCaseMetadata +from .types.test_case import RunTestCaseRequest +from .types.test_case import RunTestCaseResponse +from .types.test_case import TestCase +from .types.test_case import TestCaseError +from .types.test_case import TestCaseResult +from .types.test_case import TestConfig +from .types.test_case import TestError +from .types.test_case import TestRunDifference +from .types.test_case import TransitionCoverage +from .types.test_case import TransitionRouteGroupCoverage +from .types.test_case import UpdateTestCaseRequest +from .types.test_case import TestResult +from .types.transition_route_group import CreateTransitionRouteGroupRequest +from .types.transition_route_group import DeleteTransitionRouteGroupRequest +from .types.transition_route_group import GetTransitionRouteGroupRequest +from .types.transition_route_group import ListTransitionRouteGroupsRequest +from .types.transition_route_group import ListTransitionRouteGroupsResponse +from .types.transition_route_group import TransitionRouteGroup +from .types.transition_route_group import UpdateTransitionRouteGroupRequest +from .types.validation_message import ResourceName +from .types.validation_message import ValidationMessage +from .types.version import CreateVersionOperationMetadata +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 LoadVersionRequest +from .types.version import UpdateVersionRequest +from .types.version import Version +from .types.webhook import CreateWebhookRequest +from .types.webhook import DeleteWebhookRequest +from .types.webhook import GetWebhookRequest +from .types.webhook import ListWebhooksRequest +from .types.webhook import ListWebhooksResponse +from .types.webhook import PageInfo +from .types.webhook import SessionInfo +from .types.webhook import UpdateWebhookRequest +from .types.webhook import Webhook +from .types.webhook import WebhookRequest +from .types.webhook import WebhookResponse + +__all__ = ( + 'AgentsAsyncClient', + 'EntityTypesAsyncClient', + 'EnvironmentsAsyncClient', + 'ExperimentsAsyncClient', + 'FlowsAsyncClient', + 'IntentsAsyncClient', + 'PagesAsyncClient', + 'SecuritySettingsServiceAsyncClient', + 'SessionEntityTypesAsyncClient', + 'SessionsAsyncClient', + 'TestCasesAsyncClient', + 'TransitionRouteGroupsAsyncClient', + 'VersionsAsyncClient', + 'WebhooksAsyncClient', +'Agent', +'AgentValidationResult', +'AgentsClient', +'AudioEncoding', +'AudioInput', +'BatchDeleteTestCasesRequest', +'BatchRunTestCasesMetadata', +'BatchRunTestCasesRequest', +'BatchRunTestCasesResponse', +'CalculateCoverageRequest', +'CalculateCoverageResponse', +'ConversationTurn', +'CreateAgentRequest', +'CreateEntityTypeRequest', +'CreateEnvironmentRequest', +'CreateExperimentRequest', +'CreateFlowRequest', +'CreateIntentRequest', +'CreatePageRequest', +'CreateSecuritySettingsRequest', +'CreateSessionEntityTypeRequest', +'CreateTestCaseRequest', +'CreateTransitionRouteGroupRequest', +'CreateVersionOperationMetadata', +'CreateVersionRequest', +'CreateWebhookRequest', +'DeleteAgentRequest', +'DeleteEntityTypeRequest', +'DeleteEnvironmentRequest', +'DeleteExperimentRequest', +'DeleteFlowRequest', +'DeleteIntentRequest', +'DeletePageRequest', +'DeleteSecuritySettingsRequest', +'DeleteSessionEntityTypeRequest', +'DeleteTransitionRouteGroupRequest', +'DeleteVersionRequest', +'DeleteWebhookRequest', +'DetectIntentRequest', +'DetectIntentResponse', +'DtmfInput', +'EntityType', +'EntityTypesClient', +'Environment', +'EnvironmentsClient', +'EventHandler', +'EventInput', +'Experiment', +'ExperimentsClient', +'ExportAgentRequest', +'ExportAgentResponse', +'ExportFlowRequest', +'ExportFlowResponse', +'ExportTestCasesMetadata', +'ExportTestCasesRequest', +'ExportTestCasesResponse', +'Flow', +'FlowValidationResult', +'FlowsClient', +'Form', +'FulfillIntentRequest', +'FulfillIntentResponse', +'Fulfillment', +'GetAgentRequest', +'GetAgentValidationResultRequest', +'GetEntityTypeRequest', +'GetEnvironmentRequest', +'GetExperimentRequest', +'GetFlowRequest', +'GetFlowValidationResultRequest', +'GetIntentRequest', +'GetPageRequest', +'GetSecuritySettingsRequest', +'GetSessionEntityTypeRequest', +'GetTestCaseRequest', +'GetTestCaseResultRequest', +'GetTransitionRouteGroupRequest', +'GetVersionRequest', +'GetWebhookRequest', +'ImportFlowRequest', +'ImportFlowResponse', +'ImportTestCasesMetadata', +'ImportTestCasesRequest', +'ImportTestCasesResponse', +'InputAudioConfig', +'Intent', +'IntentCoverage', +'IntentInput', +'IntentView', +'IntentsClient', +'ListAgentsRequest', +'ListAgentsResponse', +'ListEntityTypesRequest', +'ListEntityTypesResponse', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListExperimentsRequest', +'ListExperimentsResponse', +'ListFlowsRequest', +'ListFlowsResponse', +'ListIntentsRequest', +'ListIntentsResponse', +'ListPagesRequest', +'ListPagesResponse', +'ListSecuritySettingsRequest', +'ListSecuritySettingsResponse', +'ListSessionEntityTypesRequest', +'ListSessionEntityTypesResponse', +'ListTestCaseResultsRequest', +'ListTestCaseResultsResponse', +'ListTestCasesRequest', +'ListTestCasesResponse', +'ListTransitionRouteGroupsRequest', +'ListTransitionRouteGroupsResponse', +'ListVersionsRequest', +'ListVersionsResponse', +'ListWebhooksRequest', +'ListWebhooksResponse', +'LoadVersionRequest', +'LookupEnvironmentHistoryRequest', +'LookupEnvironmentHistoryResponse', +'Match', +'MatchIntentRequest', +'MatchIntentResponse', +'NluSettings', +'OutputAudioConfig', +'OutputAudioEncoding', +'Page', +'PageInfo', +'PagesClient', +'QueryInput', +'QueryParameters', +'QueryResult', +'ResourceName', +'ResponseMessage', +'RestoreAgentRequest', +'RunTestCaseMetadata', +'RunTestCaseRequest', +'RunTestCaseResponse', +'SecuritySettings', +'SecuritySettingsServiceClient', +'SentimentAnalysisResult', +'SessionEntityType', +'SessionEntityTypesClient', +'SessionInfo', +'SessionsClient', +'SpeechModelVariant', +'SpeechToTextSettings', +'SpeechWordInfo', +'SsmlVoiceGender', +'StartExperimentRequest', +'StopExperimentRequest', +'StreamingDetectIntentRequest', +'StreamingDetectIntentResponse', +'StreamingRecognitionResult', +'SynthesizeSpeechConfig', +'TestCase', +'TestCaseError', +'TestCaseResult', +'TestCasesClient', +'TestConfig', +'TestError', +'TestResult', +'TestRunDifference', +'TextInput', +'TrainFlowRequest', +'TransitionCoverage', +'TransitionRoute', +'TransitionRouteGroup', +'TransitionRouteGroupCoverage', +'TransitionRouteGroupsClient', +'UpdateAgentRequest', +'UpdateEntityTypeRequest', +'UpdateEnvironmentRequest', +'UpdateExperimentRequest', +'UpdateFlowRequest', +'UpdateIntentRequest', +'UpdatePageRequest', +'UpdateSecuritySettingsRequest', +'UpdateSessionEntityTypeRequest', +'UpdateTestCaseRequest', +'UpdateTransitionRouteGroupRequest', +'UpdateVersionRequest', +'UpdateWebhookRequest', +'ValidateAgentRequest', +'ValidateFlowRequest', +'ValidationMessage', +'VariantsHistory', +'Version', +'VersionVariants', +'VersionsClient', +'VoiceSelectionParams', +'Webhook', +'WebhookRequest', +'WebhookResponse', +'WebhooksClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json new file mode 100644 index 00000000..6c6db5d4 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json @@ -0,0 +1,1095 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflowcx_v3", + "protoPackage": "google.cloud.dialogflow.cx.v3", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "get_agent_validation_result" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "ValidateAgent": { + "methods": [ + "validate_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "get_agent_validation_result" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "ValidateAgent": { + "methods": [ + "validate_agent" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EntityTypesAsyncClient", + "rpcs": { + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + } + } + }, + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "lookup_environment_history" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "lookup_environment_history" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Experiments": { + "clients": { + "grpc": { + "libraryClient": "ExperimentsClient", + "rpcs": { + "CreateExperiment": { + "methods": [ + "create_experiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "delete_experiment" + ] + }, + "GetExperiment": { + "methods": [ + "get_experiment" + ] + }, + "ListExperiments": { + "methods": [ + "list_experiments" + ] + }, + "StartExperiment": { + "methods": [ + "start_experiment" + ] + }, + "StopExperiment": { + "methods": [ + "stop_experiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "update_experiment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ExperimentsAsyncClient", + "rpcs": { + "CreateExperiment": { + "methods": [ + "create_experiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "delete_experiment" + ] + }, + "GetExperiment": { + "methods": [ + "get_experiment" + ] + }, + "ListExperiments": { + "methods": [ + "list_experiments" + ] + }, + "StartExperiment": { + "methods": [ + "start_experiment" + ] + }, + "StopExperiment": { + "methods": [ + "stop_experiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "update_experiment" + ] + } + } + } + } + }, + "Flows": { + "clients": { + "grpc": { + "libraryClient": "FlowsClient", + "rpcs": { + "CreateFlow": { + "methods": [ + "create_flow" + ] + }, + "DeleteFlow": { + "methods": [ + "delete_flow" + ] + }, + "ExportFlow": { + "methods": [ + "export_flow" + ] + }, + "GetFlow": { + "methods": [ + "get_flow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "get_flow_validation_result" + ] + }, + "ImportFlow": { + "methods": [ + "import_flow" + ] + }, + "ListFlows": { + "methods": [ + "list_flows" + ] + }, + "TrainFlow": { + "methods": [ + "train_flow" + ] + }, + "UpdateFlow": { + "methods": [ + "update_flow" + ] + }, + "ValidateFlow": { + "methods": [ + "validate_flow" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FlowsAsyncClient", + "rpcs": { + "CreateFlow": { + "methods": [ + "create_flow" + ] + }, + "DeleteFlow": { + "methods": [ + "delete_flow" + ] + }, + "ExportFlow": { + "methods": [ + "export_flow" + ] + }, + "GetFlow": { + "methods": [ + "get_flow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "get_flow_validation_result" + ] + }, + "ImportFlow": { + "methods": [ + "import_flow" + ] + }, + "ListFlows": { + "methods": [ + "list_flows" + ] + }, + "TrainFlow": { + "methods": [ + "train_flow" + ] + }, + "UpdateFlow": { + "methods": [ + "update_flow" + ] + }, + "ValidateFlow": { + "methods": [ + "validate_flow" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IntentsAsyncClient", + "rpcs": { + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "Pages": { + "clients": { + "grpc": { + "libraryClient": "PagesClient", + "rpcs": { + "CreatePage": { + "methods": [ + "create_page" + ] + }, + "DeletePage": { + "methods": [ + "delete_page" + ] + }, + "GetPage": { + "methods": [ + "get_page" + ] + }, + "ListPages": { + "methods": [ + "list_pages" + ] + }, + "UpdatePage": { + "methods": [ + "update_page" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PagesAsyncClient", + "rpcs": { + "CreatePage": { + "methods": [ + "create_page" + ] + }, + "DeletePage": { + "methods": [ + "delete_page" + ] + }, + "GetPage": { + "methods": [ + "get_page" + ] + }, + "ListPages": { + "methods": [ + "list_pages" + ] + }, + "UpdatePage": { + "methods": [ + "update_page" + ] + } + } + } + } + }, + "SecuritySettingsService": { + "clients": { + "grpc": { + "libraryClient": "SecuritySettingsServiceClient", + "rpcs": { + "CreateSecuritySettings": { + "methods": [ + "create_security_settings" + ] + }, + "DeleteSecuritySettings": { + "methods": [ + "delete_security_settings" + ] + }, + "GetSecuritySettings": { + "methods": [ + "get_security_settings" + ] + }, + "ListSecuritySettings": { + "methods": [ + "list_security_settings" + ] + }, + "UpdateSecuritySettings": { + "methods": [ + "update_security_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecuritySettingsServiceAsyncClient", + "rpcs": { + "CreateSecuritySettings": { + "methods": [ + "create_security_settings" + ] + }, + "DeleteSecuritySettings": { + "methods": [ + "delete_security_settings" + ] + }, + "GetSecuritySettings": { + "methods": [ + "get_security_settings" + ] + }, + "ListSecuritySettings": { + "methods": [ + "list_security_settings" + ] + }, + "UpdateSecuritySettings": { + "methods": [ + "update_security_settings" + ] + } + } + } + } + }, + "SessionEntityTypes": { + "clients": { + "grpc": { + "libraryClient": "SessionEntityTypesClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionEntityTypesAsyncClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + } + } + }, + "Sessions": { + "clients": { + "grpc": { + "libraryClient": "SessionsClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "FulfillIntent": { + "methods": [ + "fulfill_intent" + ] + }, + "MatchIntent": { + "methods": [ + "match_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "FulfillIntent": { + "methods": [ + "fulfill_intent" + ] + }, + "MatchIntent": { + "methods": [ + "match_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "TestCases": { + "clients": { + "grpc": { + "libraryClient": "TestCasesClient", + "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "batch_delete_test_cases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "batch_run_test_cases" + ] + }, + "CalculateCoverage": { + "methods": [ + "calculate_coverage" + ] + }, + "CreateTestCase": { + "methods": [ + "create_test_case" + ] + }, + "ExportTestCases": { + "methods": [ + "export_test_cases" + ] + }, + "GetTestCase": { + "methods": [ + "get_test_case" + ] + }, + "GetTestCaseResult": { + "methods": [ + "get_test_case_result" + ] + }, + "ImportTestCases": { + "methods": [ + "import_test_cases" + ] + }, + "ListTestCaseResults": { + "methods": [ + "list_test_case_results" + ] + }, + "ListTestCases": { + "methods": [ + "list_test_cases" + ] + }, + "RunTestCase": { + "methods": [ + "run_test_case" + ] + }, + "UpdateTestCase": { + "methods": [ + "update_test_case" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TestCasesAsyncClient", + "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "batch_delete_test_cases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "batch_run_test_cases" + ] + }, + "CalculateCoverage": { + "methods": [ + "calculate_coverage" + ] + }, + "CreateTestCase": { + "methods": [ + "create_test_case" + ] + }, + "ExportTestCases": { + "methods": [ + "export_test_cases" + ] + }, + "GetTestCase": { + "methods": [ + "get_test_case" + ] + }, + "GetTestCaseResult": { + "methods": [ + "get_test_case_result" + ] + }, + "ImportTestCases": { + "methods": [ + "import_test_cases" + ] + }, + "ListTestCaseResults": { + "methods": [ + "list_test_case_results" + ] + }, + "ListTestCases": { + "methods": [ + "list_test_cases" + ] + }, + "RunTestCase": { + "methods": [ + "run_test_case" + ] + }, + "UpdateTestCase": { + "methods": [ + "update_test_case" + ] + } + } + } + } + }, + "TransitionRouteGroups": { + "clients": { + "grpc": { + "libraryClient": "TransitionRouteGroupsClient", + "rpcs": { + "CreateTransitionRouteGroup": { + "methods": [ + "create_transition_route_group" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "delete_transition_route_group" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "get_transition_route_group" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "list_transition_route_groups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "update_transition_route_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TransitionRouteGroupsAsyncClient", + "rpcs": { + "CreateTransitionRouteGroup": { + "methods": [ + "create_transition_route_group" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "delete_transition_route_group" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "get_transition_route_group" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "list_transition_route_groups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "update_transition_route_group" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "LoadVersion": { + "methods": [ + "load_version" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "LoadVersion": { + "methods": [ + "load_version" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + }, + "Webhooks": { + "clients": { + "grpc": { + "libraryClient": "WebhooksClient", + "rpcs": { + "CreateWebhook": { + "methods": [ + "create_webhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "delete_webhook" + ] + }, + "GetWebhook": { + "methods": [ + "get_webhook" + ] + }, + "ListWebhooks": { + "methods": [ + "list_webhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "update_webhook" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebhooksAsyncClient", + "rpcs": { + "CreateWebhook": { + "methods": [ + "create_webhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "delete_webhook" + ] + }, + "GetWebhook": { + "methods": [ + "get_webhook" + ] + }, + "ListWebhooks": { + "methods": [ + "list_webhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "update_webhook" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed new file mode 100644 index 00000000..60fdca49 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dialogflowcx package uses inline types. diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/agents/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/__init__.py new file mode 100644 index 00000000..057c8b80 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py new file mode 100644 index 00000000..afcab083 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py @@ -0,0 +1,892 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.agents import pagers +from google.cloud.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3.types import flow +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport +from .client import AgentsClient + + +class AgentsAsyncClient: + """Service for managing [Agents][google.cloud.dialogflow.cx.v3.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) + agent_validation_result_path = staticmethod(AgentsClient.agent_validation_result_path) + parse_agent_validation_result_path = staticmethod(AgentsClient.parse_agent_validation_result_path) + environment_path = staticmethod(AgentsClient.environment_path) + parse_environment_path = staticmethod(AgentsClient.parse_environment_path) + flow_path = staticmethod(AgentsClient.flow_path) + parse_flow_path = staticmethod(AgentsClient.parse_flow_path) + flow_validation_result_path = staticmethod(AgentsClient.flow_validation_result_path) + parse_flow_validation_result_path = staticmethod(AgentsClient.parse_flow_validation_result_path) + security_settings_path = staticmethod(AgentsClient.security_settings_path) + parse_security_settings_path = staticmethod(AgentsClient.parse_security_settings_path) + common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AgentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AgentsClient.common_folder_path) + parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) + common_organization_path = staticmethod(AgentsClient.common_organization_path) + parse_common_organization_path = staticmethod(AgentsClient.parse_common_organization_path) + common_project_path = staticmethod(AgentsClient.common_project_path) + parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) + common_location_path = staticmethod(AgentsClient.common_location_path) + parse_common_location_path = staticmethod(AgentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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 list_agents(self, + request: agent.ListAgentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAgentsAsyncPager: + r"""Returns the list of all agents in the specified + location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListAgentsRequest`): + The request object. The request message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + parent (:class:`str`): + Required. The location to list all agents 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.dialogflowcx_v3.services.agents.pagers.ListAgentsAsyncPager: + The response message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + + 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.ListAgentsRequest(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_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.ListAgentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_agent(self, + request: agent.GetAgentRequest = None, + *, + name: 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.dialogflowcx_v3.types.GetAgentRequest`): + The request object. The request message for + [Agents.GetAgent][google.cloud.dialogflow.cx.v3.Agents.GetAgent]. + name (:class:`str`): + Required. The name of the agent. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = agent.GetAgentRequest(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_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(( + ("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_agent(self, + request: gcdc_agent.CreateAgentRequest = None, + *, + parent: str = None, + agent: gcdc_agent.Agent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Creates an agent in the specified location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateAgentRequest`): + The request object. The request message for + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent]. + parent (:class:`str`): + Required. The location to create a agent for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent (:class:`google.cloud.dialogflowcx_v3.types.Agent`): + Required. The agent to create. + 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.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 = gcdc_agent.CreateAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if agent is not None: + 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.create_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 update_agent(self, + request: gcdc_agent.UpdateAgentRequest = None, + *, + agent: gcdc_agent.Agent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Updates the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateAgentRequest`): + The request object. The request message for + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent]. + agent (:class:`google.cloud.dialogflowcx_v3.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. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, 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 = gcdc_agent.UpdateAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + if update_mask is not None: + 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_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.name", request.agent.name), + )), + ) + + # 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, + *, + name: 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.dialogflowcx_v3.types.DeleteAgentRequest`): + The request object. The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3.Agents.DeleteAgent]. + name (:class:`str`): + Required. The name of the agent to delete. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = agent.DeleteAgentRequest(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_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(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def export_agent(self, + request: agent.ExportAgentRequest = 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 binary file. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ExportAgentRequest`): + The request object. The request message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportAgentResponse` + The response message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + + """ + # Create or coerce a protobuf request object. + request = agent.ExportAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_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(( + ("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, + agent.ExportAgentResponse, + 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 binary file. + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, + flows) will be removed. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.RestoreAgentRequest`): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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(( + ("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=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def validate_agent(self, + request: agent.ValidateAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ValidateAgentRequest`): + The request object. The request message for + [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3.Agents.ValidateAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + request = agent.ValidateAgentRequest(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.validate_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(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_agent_validation_result(self, + request: agent.GetAgentValidationResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetAgentValidationResultRequest`): + The request object. The request message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + name (:class:`str`): + Required. The agent name. Format: + ``projects//locations//agents//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = agent.GetAgentValidationResultRequest(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_agent_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(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AgentsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py new file mode 100644 index 00000000..fb129509 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py @@ -0,0 +1,1127 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.agents import pagers +from google.cloud.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3.types import flow +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AgentsGrpcTransport +from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport + + +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.cx.v3.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,location: str,agent: str,) -> str: + """Returns a fully-qualified agent string.""" + return "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str,str]: + """Parses a agent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def agent_validation_result_path(project: str,location: str,agent: str,) -> str: + """Returns a fully-qualified agent_validation_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/validationResult".format(project=project, location=location, agent=agent, ) + + @staticmethod + def parse_agent_validation_result_path(path: str) -> Dict[str,str]: + """Parses a agent_validation_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/validationResult$", path) + return m.groupdict() if m else {} + + @staticmethod + def environment_path(project: str,location: str,agent: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_validation_result_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow_validation_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_validation_result_path(path: str) -> Dict[str,str]: + """Parses a flow_validation_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_settings_path(project: str,location: str,security_settings: str,) -> str: + """Returns a fully-qualified security_settings string.""" + return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + + @staticmethod + def parse_security_settings_path(path: str) -> Dict[str,str]: + """Parses a security_settings path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def 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 list_agents(self, + request: agent.ListAgentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAgentsPager: + r"""Returns the list of all agents in the specified + location. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListAgentsRequest): + The request object. The request message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + parent (str): + Required. The location to list all agents 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.dialogflowcx_v3.services.agents.pagers.ListAgentsPager: + The response message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + + 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.ListAgentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ListAgentsRequest): + request = agent.ListAgentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_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.ListAgentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_agent(self, + request: agent.GetAgentRequest = None, + *, + name: 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.dialogflowcx_v3.types.GetAgentRequest): + The request object. The request message for + [Agents.GetAgent][google.cloud.dialogflow.cx.v3.Agents.GetAgent]. + name (str): + Required. The name of the agent. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 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 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_agent] + + # Certain fields should be provided 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_agent(self, + request: gcdc_agent.CreateAgentRequest = None, + *, + parent: str = None, + agent: gcdc_agent.Agent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Creates an agent in the specified location. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateAgentRequest): + The request object. The request message for + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent]. + parent (str): + Required. The location to create a agent for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent (google.cloud.dialogflowcx_v3.types.Agent): + Required. The agent to create. + 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.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 gcdc_agent.CreateAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_agent.CreateAgentRequest): + request = gcdc_agent.CreateAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if agent is not None: + request.agent = agent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 update_agent(self, + request: gcdc_agent.UpdateAgentRequest = None, + *, + agent: gcdc_agent.Agent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Updates the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateAgentRequest): + The request object. The request message for + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent]. + agent (google.cloud.dialogflowcx_v3.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. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.dialogflowcx_v3.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, 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 gcdc_agent.UpdateAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_agent.UpdateAgentRequest): + request = gcdc_agent.UpdateAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + if update_mask is not None: + 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_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent.name", request.agent.name), + )), + ) + + # 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, + *, + name: 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.dialogflowcx_v3.types.DeleteAgentRequest): + The request object. The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3.Agents.DeleteAgent]. + name (str): + Required. The name of the agent to delete. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 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 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_agent] + + # Certain fields should be 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 export_agent(self, + request: agent.ExportAgentRequest = 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 binary file. + + Args: + request (google.cloud.dialogflowcx_v3.types.ExportAgentRequest): + The request object. The request message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportAgentResponse` + The response message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.ExportAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ExportAgentRequest): + request = agent.ExportAgentRequest(request) + + # 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(( + ("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, + agent.ExportAgentResponse, + 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 binary file. + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, + flows) will be removed. + + Args: + request (google.cloud.dialogflowcx_v3.types.RestoreAgentRequest): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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(( + ("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=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def validate_agent(self, + request: agent.ValidateAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Args: + request (google.cloud.dialogflowcx_v3.types.ValidateAgentRequest): + The request object. The request message for + [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3.Agents.ValidateAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.ValidateAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ValidateAgentRequest): + request = agent.ValidateAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_agent_validation_result(self, + request: agent.GetAgentValidationResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetAgentValidationResultRequest): + The request object. The request message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + name (str): + Required. The agent name. Format: + ``projects//locations//agents//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 agent.GetAgentValidationResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.GetAgentValidationResultRequest): + request = agent.GetAgentValidationResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_agent_validation_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AgentsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/pagers.py new file mode 100644 index 00000000..9a1a5e7d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import agent + + +class ListAgentsPager: + """A pager for iterating through ``list_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` + 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.ListAgentsResponse], + request: agent.ListAgentsRequest, + response: agent.ListAgentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListAgentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListAgentsResponse): + 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.ListAgentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[agent.ListAgentsResponse]: + 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 ListAgentsAsyncPager: + """A pager for iterating through ``list_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` + 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.ListAgentsResponse]], + request: agent.ListAgentsRequest, + response: agent.ListAgentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListAgentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListAgentsResponse): + 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.ListAgentsRequest(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.ListAgentsResponse]: + 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/v3/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py new file mode 100644 index 00000000..0dc0c06c --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.py new file mode 100644 index 00000000..a776e295 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.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 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.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +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-dialogflowcx', + ).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.list_agents: gapic_v1.method.wrap_method( + self.list_agents, + default_timeout=None, + client_info=client_info, + ), + self.get_agent: gapic_v1.method.wrap_method( + self.get_agent, + default_timeout=None, + client_info=client_info, + ), + self.create_agent: gapic_v1.method.wrap_method( + self.create_agent, + default_timeout=None, + client_info=client_info, + ), + self.update_agent: gapic_v1.method.wrap_method( + self.update_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.export_agent: gapic_v1.method.wrap_method( + self.export_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.validate_agent: gapic_v1.method.wrap_method( + self.validate_agent, + default_timeout=None, + client_info=client_info, + ), + self.get_agent_validation_result: gapic_v1.method.wrap_method( + self.get_agent_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 list_agents(self) -> Callable[ + [agent.ListAgentsRequest], + Union[ + agent.ListAgentsResponse, + Awaitable[agent.ListAgentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_agent(self) -> Callable[ + [agent.GetAgentRequest], + Union[ + agent.Agent, + Awaitable[agent.Agent] + ]]: + raise NotImplementedError() + + @property + def create_agent(self) -> Callable[ + [gcdc_agent.CreateAgentRequest], + Union[ + gcdc_agent.Agent, + Awaitable[gcdc_agent.Agent] + ]]: + raise NotImplementedError() + + @property + def update_agent(self) -> Callable[ + [gcdc_agent.UpdateAgentRequest], + Union[ + gcdc_agent.Agent, + Awaitable[gcdc_agent.Agent] + ]]: + raise NotImplementedError() + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + 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 validate_agent(self) -> Callable[ + [agent.ValidateAgentRequest], + Union[ + agent.AgentValidationResult, + Awaitable[agent.AgentValidationResult] + ]]: + raise NotImplementedError() + + @property + def get_agent_validation_result(self) -> Callable[ + [agent.GetAgentValidationResultRequest], + Union[ + agent.AgentValidationResult, + Awaitable[agent.AgentValidationResult] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'AgentsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py new file mode 100644 index 00000000..21689209 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py @@ -0,0 +1,485 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +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.cx.v3.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 list_agents(self) -> Callable[ + [agent.ListAgentsRequest], + agent.ListAgentsResponse]: + r"""Return a callable for the list agents method over gRPC. + + Returns the list of all agents in the specified + location. + + Returns: + Callable[[~.ListAgentsRequest], + ~.ListAgentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_agents' not in self._stubs: + self._stubs['list_agents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/ListAgents', + request_serializer=agent.ListAgentsRequest.serialize, + response_deserializer=agent.ListAgentsResponse.deserialize, + ) + return self._stubs['list_agents'] + + @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.cx.v3.Agents/GetAgent', + request_serializer=agent.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs['get_agent'] + + @property + def create_agent(self) -> Callable[ + [gcdc_agent.CreateAgentRequest], + gcdc_agent.Agent]: + r"""Return a callable for the create agent method over gRPC. + + Creates an agent in the specified location. + + Returns: + Callable[[~.CreateAgentRequest], + ~.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 'create_agent' not in self._stubs: + self._stubs['create_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/CreateAgent', + request_serializer=gcdc_agent.CreateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['create_agent'] + + @property + def update_agent(self) -> Callable[ + [gcdc_agent.UpdateAgentRequest], + gcdc_agent.Agent]: + r"""Return a callable for the update agent method over gRPC. + + Updates the specified agent. + + Returns: + Callable[[~.UpdateAgentRequest], + ~.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 'update_agent' not in self._stubs: + self._stubs['update_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/UpdateAgent', + request_serializer=gcdc_agent.UpdateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['update_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.cx.v3.Agents/DeleteAgent', + request_serializer=agent.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_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 binary file. + + 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.cx.v3.Agents/ExportAgent', + request_serializer=agent.ExportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_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 binary file. + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, + flows) will be removed. + + 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.cx.v3.Agents/RestoreAgent', + request_serializer=agent.RestoreAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_agent'] + + @property + def validate_agent(self) -> Callable[ + [agent.ValidateAgentRequest], + agent.AgentValidationResult]: + r"""Return a callable for the validate agent method over gRPC. + + Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Returns: + Callable[[~.ValidateAgentRequest], + ~.AgentValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_agent' not in self._stubs: + self._stubs['validate_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/ValidateAgent', + request_serializer=agent.ValidateAgentRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['validate_agent'] + + @property + def get_agent_validation_result(self) -> Callable[ + [agent.GetAgentValidationResultRequest], + agent.AgentValidationResult]: + r"""Return a callable for the get agent validation result method over gRPC. + + Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Returns: + Callable[[~.GetAgentValidationResultRequest], + ~.AgentValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_validation_result' not in self._stubs: + self._stubs['get_agent_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/GetAgentValidationResult', + request_serializer=agent.GetAgentValidationResultRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['get_agent_validation_result'] + + +__all__ = ( + 'AgentsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py new file mode 100644 index 00000000..3b3ac651 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py @@ -0,0 +1,489 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +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.cx.v3.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 list_agents(self) -> Callable[ + [agent.ListAgentsRequest], + Awaitable[agent.ListAgentsResponse]]: + r"""Return a callable for the list agents method over gRPC. + + Returns the list of all agents in the specified + location. + + Returns: + Callable[[~.ListAgentsRequest], + Awaitable[~.ListAgentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_agents' not in self._stubs: + self._stubs['list_agents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/ListAgents', + request_serializer=agent.ListAgentsRequest.serialize, + response_deserializer=agent.ListAgentsResponse.deserialize, + ) + return self._stubs['list_agents'] + + @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.cx.v3.Agents/GetAgent', + request_serializer=agent.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs['get_agent'] + + @property + def create_agent(self) -> Callable[ + [gcdc_agent.CreateAgentRequest], + Awaitable[gcdc_agent.Agent]]: + r"""Return a callable for the create agent method over gRPC. + + Creates an agent in the specified location. + + Returns: + Callable[[~.CreateAgentRequest], + 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 'create_agent' not in self._stubs: + self._stubs['create_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/CreateAgent', + request_serializer=gcdc_agent.CreateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['create_agent'] + + @property + def update_agent(self) -> Callable[ + [gcdc_agent.UpdateAgentRequest], + Awaitable[gcdc_agent.Agent]]: + r"""Return a callable for the update agent method over gRPC. + + Updates the specified agent. + + Returns: + Callable[[~.UpdateAgentRequest], + 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 'update_agent' not in self._stubs: + self._stubs['update_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/UpdateAgent', + request_serializer=gcdc_agent.UpdateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['update_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.cx.v3.Agents/DeleteAgent', + request_serializer=agent.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_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 binary file. + + 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.cx.v3.Agents/ExportAgent', + request_serializer=agent.ExportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_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 binary file. + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, + flows) will be removed. + + 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.cx.v3.Agents/RestoreAgent', + request_serializer=agent.RestoreAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_agent'] + + @property + def validate_agent(self) -> Callable[ + [agent.ValidateAgentRequest], + Awaitable[agent.AgentValidationResult]]: + r"""Return a callable for the validate agent method over gRPC. + + Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Returns: + Callable[[~.ValidateAgentRequest], + Awaitable[~.AgentValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_agent' not in self._stubs: + self._stubs['validate_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/ValidateAgent', + request_serializer=agent.ValidateAgentRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['validate_agent'] + + @property + def get_agent_validation_result(self) -> Callable[ + [agent.GetAgentValidationResultRequest], + Awaitable[agent.AgentValidationResult]]: + r"""Return a callable for the get agent validation result method over gRPC. + + Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Returns: + Callable[[~.GetAgentValidationResultRequest], + Awaitable[~.AgentValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_validation_result' not in self._stubs: + self._stubs['get_agent_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Agents/GetAgentValidationResult', + request_serializer=agent.GetAgentValidationResultRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['get_agent_validation_result'] + + +__all__ = ( + 'AgentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py new file mode 100644 index 00000000..82dfe86f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py new file mode 100644 index 00000000..b032bc8d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py @@ -0,0 +1,659 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.entity_types import pagers +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.protobuf import field_mask_pb2 # 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.cx.v3.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, + 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.dialogflowcx_v3.types.ListEntityTypesRequest`): + The request object. The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. + parent (:class:`str`): + Required. The agent to list all entity types for. + Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.entity_types.pagers.ListEntityTypesAsyncPager: + The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.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]) + if request is not 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 + + # 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, + 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.dialogflowcx_v3.types.GetEntityTypeRequest`): + The request object. The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.GetEntityType]. + name (:class:`str`): + Required. The name of the entity type. Format: + ``projects//locations//agents//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. + + Returns: + google.cloud.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not 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 + + # 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: gcdc_entity_type.CreateEntityTypeRequest = None, + *, + parent: str = None, + entity_type: gcdc_entity_type.EntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateEntityTypeRequest`): + The request object. The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.CreateEntityType]. + parent (:class:`str`): + Required. The agent to create a entity type for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type (:class:`google.cloud.dialogflowcx_v3.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. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_entity_type.CreateEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type is not None: + request.entity_type = 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_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: gcdc_entity_type.UpdateEntityTypeRequest = None, + *, + entity_type: gcdc_entity_type.EntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Updates the specified entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateEntityTypeRequest`): + The request object. The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. + entity_type (:class:`google.cloud.dialogflowcx_v3.types.EntityType`): + 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. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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, 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 = gcdc_entity_type.UpdateEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entity_type is not None: + request.entity_type = entity_type + if update_mask is not None: + 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.dialogflowcx_v3.types.DeleteEntityTypeRequest`): + The request object. The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.DeleteEntityType]. + name (:class:`str`): + Required. The name of the entity type to delete. Format: + ``projects//locations//agents//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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EntityTypesAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py new file mode 100644 index 00000000..2570459d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py @@ -0,0 +1,846 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.entity_types import pagers +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.protobuf import field_mask_pb2 # 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.cx.v3.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,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?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, 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, + 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.dialogflowcx_v3.types.ListEntityTypesRequest): + The request object. The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. + parent (str): + Required. The agent to list all entity types for. + Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.entity_types.pagers.ListEntityTypesPager: + The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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 + + # 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, + 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.dialogflowcx_v3.types.GetEntityTypeRequest): + The request object. The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.GetEntityType]. + name (str): + Required. The name of the entity type. Format: + ``projects//locations//agents//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. + + Returns: + google.cloud.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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 + + # 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: gcdc_entity_type.CreateEntityTypeRequest = None, + *, + parent: str = None, + entity_type: gcdc_entity_type.EntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateEntityTypeRequest): + The request object. The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.CreateEntityType]. + parent (str): + Required. The agent to create a entity type for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type (google.cloud.dialogflowcx_v3.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. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_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, gcdc_entity_type.CreateEntityTypeRequest): + request = gcdc_entity_type.CreateEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type is not None: + request.entity_type = entity_type + + # 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: gcdc_entity_type.UpdateEntityTypeRequest = None, + *, + entity_type: gcdc_entity_type.EntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Updates the specified entity type. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateEntityTypeRequest): + The request object. The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. + entity_type (google.cloud.dialogflowcx_v3.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. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.dialogflowcx_v3.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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, 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 gcdc_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, gcdc_entity_type.UpdateEntityTypeRequest): + request = gcdc_entity_type.UpdateEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entity_type is not None: + request.entity_type = entity_type + if update_mask is not None: + 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.dialogflowcx_v3.types.DeleteEntityTypeRequest): + The request object. The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.DeleteEntityType]. + name (str): + Required. The name of the entity type to delete. Format: + ``projects//locations//agents//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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EntityTypesClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py new file mode 100644 index 00000000..6b479cd6 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import entity_type + + +class ListEntityTypesPager: + """A pager for iterating through ``list_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.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/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py new file mode 100644 index 00000000..1a2aa82d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py new file mode 100644 index 00000000..f6eb1fb8 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/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.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +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, + ), + } + + @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[ + [gcdc_entity_type.CreateEntityTypeRequest], + Union[ + gcdc_entity_type.EntityType, + Awaitable[gcdc_entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def update_entity_type(self) -> Callable[ + [gcdc_entity_type.UpdateEntityTypeRequest], + Union[ + gcdc_entity_type.EntityType, + Awaitable[gcdc_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() + + +__all__ = ( + 'EntityTypesTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py new file mode 100644 index 00000000..32aea14e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/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.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO + + +class EntityTypesGrpcTransport(EntityTypesTransport): + """gRPC backend transport for EntityTypes. + + Service for managing + [EntityTypes][google.cloud.dialogflow.cx.v3.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] = {} + + 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_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.cx.v3.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.cx.v3.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[ + [gcdc_entity_type.CreateEntityTypeRequest], + gcdc_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.cx.v3.EntityTypes/CreateEntityType', + request_serializer=gcdc_entity_type.CreateEntityTypeRequest.serialize, + response_deserializer=gcdc_entity_type.EntityType.deserialize, + ) + return self._stubs['create_entity_type'] + + @property + def update_entity_type(self) -> Callable[ + [gcdc_entity_type.UpdateEntityTypeRequest], + gcdc_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.cx.v3.EntityTypes/UpdateEntityType', + request_serializer=gcdc_entity_type.UpdateEntityTypeRequest.serialize, + response_deserializer=gcdc_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.cx.v3.EntityTypes/DeleteEntityType', + request_serializer=entity_type.DeleteEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entity_type'] + + +__all__ = ( + 'EntityTypesGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py new file mode 100644 index 00000000..1ae72cb2 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/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.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.protobuf import empty_pb2 # 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.cx.v3.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] = {} + + 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_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.cx.v3.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.cx.v3.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[ + [gcdc_entity_type.CreateEntityTypeRequest], + Awaitable[gcdc_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.cx.v3.EntityTypes/CreateEntityType', + request_serializer=gcdc_entity_type.CreateEntityTypeRequest.serialize, + response_deserializer=gcdc_entity_type.EntityType.deserialize, + ) + return self._stubs['create_entity_type'] + + @property + def update_entity_type(self) -> Callable[ + [gcdc_entity_type.UpdateEntityTypeRequest], + Awaitable[gcdc_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.cx.v3.EntityTypes/UpdateEntityType', + request_serializer=gcdc_entity_type.UpdateEntityTypeRequest.serialize, + response_deserializer=gcdc_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.cx.v3.EntityTypes/DeleteEntityType', + request_serializer=entity_type.DeleteEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entity_type'] + + +__all__ = ( + 'EntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/__init__.py new file mode 100644 index 00000000..a3ad29ec --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py new file mode 100644 index 00000000..54621b60 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py @@ -0,0 +1,723 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.environments import pagers +from google.cloud.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .client import EnvironmentsClient + + +class EnvironmentsAsyncClient: + """Service for managing + [Environments][google.cloud.dialogflow.cx.v3.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) + version_path = staticmethod(EnvironmentsClient.version_path) + parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) + common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) + common_project_path = staticmethod(EnvironmentsClient.common_project_path) + parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) + common_location_path = staticmethod(EnvironmentsClient.common_location_path) + parse_common_location_path = staticmethod(EnvironmentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @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 environments in the specified + [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListEnvironmentsRequest`): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to list all + environments for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.environments.pagers.ListEnvironmentsAsyncPager: + The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.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, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetEnvironmentRequest`): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3.Environments.GetEnvironment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Environment: + Represents an environment for an + agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = environment.GetEnvironmentRequest(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_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: gcdc_environment.CreateEnvironmentRequest = None, + *, + parent: str = None, + environment: gcdc_environment.Environment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates an + [Environment][google.cloud.dialogflow.cx.v3.Environment] in the + specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateEnvironmentRequest`): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3.Environments.CreateEnvironment]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (:class:`google.cloud.dialogflowcx_v3.types.Environment`): + Required. The environment to create. + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, environment]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_environment.CreateEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if environment is not None: + request.environment = environment + + # 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def update_environment(self, + request: gcdc_environment.UpdateEnvironmentRequest = None, + *, + environment: gcdc_environment.Environment = 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 + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateEnvironmentRequest`): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3.Environments.UpdateEnvironment]. + environment (:class:`google.cloud.dialogflowcx_v3.types.Environment`): + Required. The environment to update. + This corresponds to the ``environment`` 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([environment, 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 = gcdc_environment.UpdateEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if environment is not None: + request.environment = environment + if update_mask is not None: + 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_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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def delete_environment(self, + request: environment.DeleteEnvironmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteEnvironmentRequest`): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3.Environments.DeleteEnvironment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to delete. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = environment.DeleteEnvironmentRequest(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_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 lookup_environment_history(self, + request: environment.LookupEnvironmentHistoryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.LookupEnvironmentHistoryAsyncPager: + r"""Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest`): + The request object. The request message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + name (:class:`str`): + Required. Resource name of the environment to look up + the history for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.environments.pagers.LookupEnvironmentHistoryAsyncPager: + The response message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + + 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([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 = environment.LookupEnvironmentHistoryRequest(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.lookup_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(( + ("name", request.name), + )), + ) + + # 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.LookupEnvironmentHistoryAsyncPager( + 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EnvironmentsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py new file mode 100644 index 00000000..3a42717f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py @@ -0,0 +1,919 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.environments import pagers +from google.cloud.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EnvironmentsGrpcTransport +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +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.cx.v3.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,location: str,agent: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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, 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 environments in the specified + [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListEnvironmentsRequest): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to list all + environments for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.environments.pagers.ListEnvironmentsPager: + The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.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, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetEnvironmentRequest): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3.Environments.GetEnvironment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Environment: + Represents an environment for an + agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 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) + # 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_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: gcdc_environment.CreateEnvironmentRequest = None, + *, + parent: str = None, + environment: gcdc_environment.Environment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates an + [Environment][google.cloud.dialogflow.cx.v3.Environment] in the + specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateEnvironmentRequest): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3.Environments.CreateEnvironment]. + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (google.cloud.dialogflowcx_v3.types.Environment): + Required. The environment to create. + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, environment]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_environment.CreateEnvironmentRequest): + request = gcdc_environment.CreateEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if environment is not None: + request.environment = environment + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def update_environment(self, + request: gcdc_environment.UpdateEnvironmentRequest = None, + *, + environment: gcdc_environment.Environment = 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 + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateEnvironmentRequest): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3.Environments.UpdateEnvironment]. + environment (google.cloud.dialogflowcx_v3.types.Environment): + Required. The environment to update. + This corresponds to the ``environment`` 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([environment, 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 gcdc_environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_environment.UpdateEnvironmentRequest): + request = gcdc_environment.UpdateEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if environment is not None: + request.environment = environment + if update_mask is not None: + 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_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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def delete_environment(self, + request: environment.DeleteEnvironmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3.types.DeleteEnvironmentRequest): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3.Environments.DeleteEnvironment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to delete. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 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) + # 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_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 lookup_environment_history(self, + request: environment.LookupEnvironmentHistoryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.LookupEnvironmentHistoryPager: + r"""Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest): + The request object. The request message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + name (str): + Required. Resource name of the environment to look up + the history for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.environments.pagers.LookupEnvironmentHistoryPager: + The response message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + + 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([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 environment.LookupEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.LookupEnvironmentHistoryRequest): + request = environment.LookupEnvironmentHistoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.lookup_environment_history] + + # Certain fields should be provided 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.LookupEnvironmentHistoryPager( + 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EnvironmentsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/pagers.py new file mode 100644 index 00000000..2f79748a --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import environment + + +class ListEnvironmentsPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.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 LookupEnvironmentHistoryPager: + """A pager for iterating through ``lookup_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` object, and + provides an ``__iter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``LookupEnvironmentHistory`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` + 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.LookupEnvironmentHistoryResponse], + request: environment.LookupEnvironmentHistoryRequest, + response: environment.LookupEnvironmentHistoryResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse): + 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.LookupEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[environment.LookupEnvironmentHistoryResponse]: + 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 LookupEnvironmentHistoryAsyncPager: + """A pager for iterating through ``lookup_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``LookupEnvironmentHistory`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` + 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.LookupEnvironmentHistoryResponse]], + request: environment.LookupEnvironmentHistoryRequest, + response: environment.LookupEnvironmentHistoryResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse): + 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.LookupEnvironmentHistoryRequest(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.LookupEnvironmentHistoryResponse]: + 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) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py new file mode 100644 index 00000000..fac90efe --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.py new file mode 100644 index 00000000..e84ea41d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.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. +# +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.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +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-dialogflowcx', + ).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.lookup_environment_history: gapic_v1.method.wrap_method( + self.lookup_environment_history, + 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_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[ + [gcdc_environment.CreateEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_environment(self) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def lookup_environment_history(self) -> Callable[ + [environment.LookupEnvironmentHistoryRequest], + Union[ + environment.LookupEnvironmentHistoryResponse, + Awaitable[environment.LookupEnvironmentHistoryResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'EnvironmentsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py new file mode 100644 index 00000000..85af1ac2 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py @@ -0,0 +1,407 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +from google.longrunning import operations_pb2 # type: ignore +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.cx.v3.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] = {} + 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_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + environment.ListEnvironmentsResponse]: + r"""Return a callable for the list environments method over gRPC. + + Returns the list of all environments in the specified + [Agent][google.cloud.dialogflow.cx.v3.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.cx.v3.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 + [Environment][google.cloud.dialogflow.cx.v3.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.cx.v3.Environments/GetEnvironment', + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def create_environment(self) -> Callable[ + [gcdc_environment.CreateEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the create environment method over gRPC. + + Creates an + [Environment][google.cloud.dialogflow.cx.v3.Environment] in the + specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['create_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/CreateEnvironment', + request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_environment'] + + @property + def update_environment(self) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/UpdateEnvironment', + request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + 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 + [Environment][google.cloud.dialogflow.cx.v3.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.cx.v3.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def lookup_environment_history(self) -> Callable[ + [environment.LookupEnvironmentHistoryRequest], + environment.LookupEnvironmentHistoryResponse]: + r"""Return a callable for the lookup environment history method over gRPC. + + Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.LookupEnvironmentHistoryRequest], + ~.LookupEnvironmentHistoryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'lookup_environment_history' not in self._stubs: + self._stubs['lookup_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/LookupEnvironmentHistory', + request_serializer=environment.LookupEnvironmentHistoryRequest.serialize, + response_deserializer=environment.LookupEnvironmentHistoryResponse.deserialize, + ) + return self._stubs['lookup_environment_history'] + + +__all__ = ( + 'EnvironmentsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py new file mode 100644 index 00000000..347981c5 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py @@ -0,0 +1,411 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import EnvironmentsGrpcTransport + + +class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): + """gRPC AsyncIO backend transport for Environments. + + Service for managing + [Environments][google.cloud.dialogflow.cx.v3.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] = {} + 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_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + Awaitable[environment.ListEnvironmentsResponse]]: + r"""Return a callable for the list environments method over gRPC. + + Returns the list of all environments in the specified + [Agent][google.cloud.dialogflow.cx.v3.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.cx.v3.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 + [Environment][google.cloud.dialogflow.cx.v3.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.cx.v3.Environments/GetEnvironment', + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def create_environment(self) -> Callable[ + [gcdc_environment.CreateEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create environment method over gRPC. + + Creates an + [Environment][google.cloud.dialogflow.cx.v3.Environment] in the + specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. + + Returns: + Callable[[~.CreateEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['create_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/CreateEnvironment', + request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_environment'] + + @property + def update_environment(self) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/UpdateEnvironment', + request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + 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 + [Environment][google.cloud.dialogflow.cx.v3.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.cx.v3.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def lookup_environment_history(self) -> Callable[ + [environment.LookupEnvironmentHistoryRequest], + Awaitable[environment.LookupEnvironmentHistoryResponse]]: + r"""Return a callable for the lookup environment history method over gRPC. + + Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.LookupEnvironmentHistoryRequest], + Awaitable[~.LookupEnvironmentHistoryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'lookup_environment_history' not in self._stubs: + self._stubs['lookup_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Environments/LookupEnvironmentHistory', + request_serializer=environment.LookupEnvironmentHistoryRequest.serialize, + response_deserializer=environment.LookupEnvironmentHistoryResponse.deserialize, + ) + return self._stubs['lookup_environment_history'] + + +__all__ = ( + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__init__.py new file mode 100644 index 00000000..6d4dd817 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__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 ExperimentsClient +from .async_client import ExperimentsAsyncClient + +__all__ = ( + 'ExperimentsClient', + 'ExperimentsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py new file mode 100644 index 00000000..03150133 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py @@ -0,0 +1,738 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.experiments import pagers +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport +from .client import ExperimentsClient + + +class ExperimentsAsyncClient: + """Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + """ + + _client: ExperimentsClient + + DEFAULT_ENDPOINT = ExperimentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ExperimentsClient.DEFAULT_MTLS_ENDPOINT + + experiment_path = staticmethod(ExperimentsClient.experiment_path) + parse_experiment_path = staticmethod(ExperimentsClient.parse_experiment_path) + version_path = staticmethod(ExperimentsClient.version_path) + parse_version_path = staticmethod(ExperimentsClient.parse_version_path) + common_billing_account_path = staticmethod(ExperimentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ExperimentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ExperimentsClient.common_folder_path) + parse_common_folder_path = staticmethod(ExperimentsClient.parse_common_folder_path) + common_organization_path = staticmethod(ExperimentsClient.common_organization_path) + parse_common_organization_path = staticmethod(ExperimentsClient.parse_common_organization_path) + common_project_path = staticmethod(ExperimentsClient.common_project_path) + parse_common_project_path = staticmethod(ExperimentsClient.parse_common_project_path) + common_location_path = staticmethod(ExperimentsClient.common_location_path) + parse_common_location_path = staticmethod(ExperimentsClient.parse_common_location_path) + + @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: + ExperimentsAsyncClient: The constructed client. + """ + return ExperimentsClient.from_service_account_info.__func__(ExperimentsAsyncClient, 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: + ExperimentsAsyncClient: The constructed client. + """ + return ExperimentsClient.from_service_account_file.__func__(ExperimentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ExperimentsTransport: + """Returns the transport used by the client instance. + + Returns: + ExperimentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ExperimentsClient).get_transport_class, type(ExperimentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ExperimentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the experiments 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, ~.ExperimentsTransport]): 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 = ExperimentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_experiments(self, + request: experiment.ListExperimentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExperimentsAsyncPager: + r"""Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListExperimentsRequest`): + The request object. The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + parent (:class:`str`): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to list all environments for. Format: + ``projects//locations//agents//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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.experiments.pagers.ListExperimentsAsyncPager: + The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + 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 = experiment.ListExperimentsRequest(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_experiments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListExperimentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_experiment(self, + request: experiment.GetExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetExperimentRequest`): + The request object. The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.GetExperimentRequest(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_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_experiment(self, + request: gcdc_experiment.CreateExperimentRequest = None, + *, + parent: str = None, + experiment: gcdc_experiment.Experiment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateExperimentRequest`): + The request object. The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + experiment (:class:`google.cloud.dialogflowcx_v3.types.Experiment`): + Required. The experiment to create. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, experiment]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_experiment.CreateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if experiment is not None: + request.experiment = experiment + + # 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_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_experiment(self, + request: gcdc_experiment.UpdateExperimentRequest = None, + *, + experiment: gcdc_experiment.Experiment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest`): + The request object. The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. + experiment (:class:`google.cloud.dialogflowcx_v3.types.Experiment`): + Required. The experiment to update. + This corresponds to the ``experiment`` 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.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([experiment, 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 = gcdc_experiment.UpdateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if experiment is not None: + request.experiment = experiment + if update_mask is not None: + 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_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("experiment.name", request.experiment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_experiment(self, + request: experiment.DeleteExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest`): + The request object. The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = experiment.DeleteExperimentRequest(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_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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 start_experiment(self, + request: experiment.StartExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.StartExperimentRequest`): + The request object. The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to start. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.StartExperimentRequest(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.start_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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 stop_experiment(self, + request: experiment.StopExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.StopExperimentRequest`): + The request object. The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to stop. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.StopExperimentRequest(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.stop_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ExperimentsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py new file mode 100644 index 00000000..f962e435 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py @@ -0,0 +1,934 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.experiments import pagers +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ExperimentsGrpcTransport +from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport + + +class ExperimentsClientMeta(type): + """Metaclass for the Experiments 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[ExperimentsTransport]] + _transport_registry["grpc"] = ExperimentsGrpcTransport + _transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ExperimentsTransport]: + """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 ExperimentsClient(metaclass=ExperimentsClientMeta): + """Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + """ + + @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: + ExperimentsClient: 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: + ExperimentsClient: 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) -> ExperimentsTransport: + """Returns the transport used by the client instance. + + Returns: + ExperimentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def experiment_path(project: str,location: str,agent: str,environment: str,experiment: str,) -> str: + """Returns a fully-qualified experiment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format(project=project, location=location, agent=agent, environment=environment, experiment=experiment, ) + + @staticmethod + def parse_experiment_path(path: str) -> Dict[str,str]: + """Parses a experiment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/experiments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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, ExperimentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the experiments 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, ExperimentsTransport]): 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, ExperimentsTransport): + # transport is a ExperimentsTransport 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_experiments(self, + request: experiment.ListExperimentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExperimentsPager: + r"""Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListExperimentsRequest): + The request object. The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + parent (str): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to list all environments for. Format: + ``projects//locations//agents//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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.experiments.pagers.ListExperimentsPager: + The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + 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 experiment.ListExperimentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.ListExperimentsRequest): + request = experiment.ListExperimentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_experiments] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListExperimentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_experiment(self, + request: experiment.GetExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetExperimentRequest): + The request object. The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.GetExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.GetExperimentRequest): + request = experiment.GetExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_experiment] + + # Certain fields should be provided 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_experiment(self, + request: gcdc_experiment.CreateExperimentRequest = None, + *, + parent: str = None, + experiment: gcdc_experiment.Experiment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateExperimentRequest): + The request object. The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + experiment (google.cloud.dialogflowcx_v3.types.Experiment): + Required. The experiment to create. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, experiment]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_experiment.CreateExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_experiment.CreateExperimentRequest): + request = gcdc_experiment.CreateExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if experiment is not None: + request.experiment = experiment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_experiment(self, + request: gcdc_experiment.UpdateExperimentRequest = None, + *, + experiment: gcdc_experiment.Experiment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest): + The request object. The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. + experiment (google.cloud.dialogflowcx_v3.types.Experiment): + Required. The experiment to update. + This corresponds to the ``experiment`` 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.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([experiment, 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 gcdc_experiment.UpdateExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_experiment.UpdateExperimentRequest): + request = gcdc_experiment.UpdateExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if experiment is not None: + request.experiment = experiment + if update_mask is not None: + 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_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("experiment.name", request.experiment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_experiment(self, + request: experiment.DeleteExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Args: + request (google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest): + The request object. The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 experiment.DeleteExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.DeleteExperimentRequest): + request = experiment.DeleteExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_experiment] + + # Certain fields should be 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 start_experiment(self, + request: experiment.StartExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Args: + request (google.cloud.dialogflowcx_v3.types.StartExperimentRequest): + The request object. The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. + name (str): + Required. Resource name of the experiment to start. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.StartExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.StartExperimentRequest): + request = experiment.StartExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.start_experiment] + + # Certain fields should be provided 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 stop_experiment(self, + request: experiment.StopExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Args: + request (google.cloud.dialogflowcx_v3.types.StopExperimentRequest): + The request object. The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. + name (str): + Required. Resource name of the experiment to stop. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.StopExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.StopExperimentRequest): + request = experiment.StopExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stop_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ExperimentsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/pagers.py new file mode 100644 index 00000000..045ae8fb --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/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.dialogflowcx_v3.types import experiment + + +class ListExperimentsPager: + """A pager for iterating through ``list_experiments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``experiments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExperiments`` requests and continue to iterate + through the ``experiments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` + 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[..., experiment.ListExperimentsResponse], + request: experiment.ListExperimentsRequest, + response: experiment.ListExperimentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListExperimentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListExperimentsResponse): + 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 = experiment.ListExperimentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[experiment.ListExperimentsResponse]: + 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[experiment.Experiment]: + for page in self.pages: + yield from page.experiments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListExperimentsAsyncPager: + """A pager for iterating through ``list_experiments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``experiments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExperiments`` requests and continue to iterate + through the ``experiments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` + 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[experiment.ListExperimentsResponse]], + request: experiment.ListExperimentsRequest, + response: experiment.ListExperimentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListExperimentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListExperimentsResponse): + 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 = experiment.ListExperimentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[experiment.ListExperimentsResponse]: + 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[experiment.Experiment]: + async def async_generator(): + async for page in self.pages: + for response in page.experiments: + 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/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py new file mode 100644 index 00000000..80f4c26e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/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 ExperimentsTransport +from .grpc import ExperimentsGrpcTransport +from .grpc_asyncio import ExperimentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ExperimentsTransport]] +_transport_registry['grpc'] = ExperimentsGrpcTransport +_transport_registry['grpc_asyncio'] = ExperimentsGrpcAsyncIOTransport + +__all__ = ( + 'ExperimentsTransport', + 'ExperimentsGrpcTransport', + 'ExperimentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py new file mode 100644 index 00000000..82dd4069 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +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-dialogflowcx', + ).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 ExperimentsTransport(abc.ABC): + """Abstract transport class for Experiments.""" + + 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_experiments: gapic_v1.method.wrap_method( + self.list_experiments, + default_timeout=None, + client_info=client_info, + ), + self.get_experiment: gapic_v1.method.wrap_method( + self.get_experiment, + default_timeout=None, + client_info=client_info, + ), + self.create_experiment: gapic_v1.method.wrap_method( + self.create_experiment, + default_timeout=None, + client_info=client_info, + ), + self.update_experiment: gapic_v1.method.wrap_method( + self.update_experiment, + default_timeout=None, + client_info=client_info, + ), + self.delete_experiment: gapic_v1.method.wrap_method( + self.delete_experiment, + default_timeout=None, + client_info=client_info, + ), + self.start_experiment: gapic_v1.method.wrap_method( + self.start_experiment, + default_timeout=None, + client_info=client_info, + ), + self.stop_experiment: gapic_v1.method.wrap_method( + self.stop_experiment, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_experiments(self) -> Callable[ + [experiment.ListExperimentsRequest], + Union[ + experiment.ListExperimentsResponse, + Awaitable[experiment.ListExperimentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_experiment(self) -> Callable[ + [experiment.GetExperimentRequest], + Union[ + experiment.Experiment, + Awaitable[experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def create_experiment(self) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], + Union[ + gcdc_experiment.Experiment, + Awaitable[gcdc_experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def update_experiment(self) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], + Union[ + gcdc_experiment.Experiment, + Awaitable[gcdc_experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def delete_experiment(self) -> Callable[ + [experiment.DeleteExperimentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def start_experiment(self) -> Callable[ + [experiment.StartExperimentRequest], + Union[ + experiment.Experiment, + Awaitable[experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def stop_experiment(self) -> Callable[ + [experiment.StopExperimentRequest], + Union[ + experiment.Experiment, + Awaitable[experiment.Experiment] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ExperimentsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py new file mode 100644 index 00000000..3e5a9901 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.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 Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 # type: ignore +from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO + + +class ExperimentsGrpcTransport(ExperimentsTransport): + """gRPC backend transport for Experiments. + + Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + + 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_experiments(self) -> Callable[ + [experiment.ListExperimentsRequest], + experiment.ListExperimentsResponse]: + r"""Return a callable for the list experiments method over gRPC. + + Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.ListExperimentsRequest], + ~.ListExperimentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_experiments' not in self._stubs: + self._stubs['list_experiments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/ListExperiments', + request_serializer=experiment.ListExperimentsRequest.serialize, + response_deserializer=experiment.ListExperimentsResponse.deserialize, + ) + return self._stubs['list_experiments'] + + @property + def get_experiment(self) -> Callable[ + [experiment.GetExperimentRequest], + experiment.Experiment]: + r"""Return a callable for the get experiment method over gRPC. + + Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.GetExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_experiment' not in self._stubs: + self._stubs['get_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/GetExperiment', + request_serializer=experiment.GetExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['get_experiment'] + + @property + def create_experiment(self) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], + gcdc_experiment.Experiment]: + r"""Return a callable for the create experiment method over gRPC. + + Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.CreateExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_experiment' not in self._stubs: + self._stubs['create_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/CreateExperiment', + request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['create_experiment'] + + @property + def update_experiment(self) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], + gcdc_experiment.Experiment]: + r"""Return a callable for the update experiment method over gRPC. + + Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.UpdateExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_experiment' not in self._stubs: + self._stubs['update_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/UpdateExperiment', + request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['update_experiment'] + + @property + def delete_experiment(self) -> Callable[ + [experiment.DeleteExperimentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete experiment method over gRPC. + + Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.DeleteExperimentRequest], + ~.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_experiment' not in self._stubs: + self._stubs['delete_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/DeleteExperiment', + request_serializer=experiment.DeleteExperimentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_experiment'] + + @property + def start_experiment(self) -> Callable[ + [experiment.StartExperimentRequest], + experiment.Experiment]: + r"""Return a callable for the start experiment method over gRPC. + + Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Returns: + Callable[[~.StartExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_experiment' not in self._stubs: + self._stubs['start_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/StartExperiment', + request_serializer=experiment.StartExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['start_experiment'] + + @property + def stop_experiment(self) -> Callable[ + [experiment.StopExperimentRequest], + experiment.Experiment]: + r"""Return a callable for the stop experiment method over gRPC. + + Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Returns: + Callable[[~.StopExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_experiment' not in self._stubs: + self._stubs['stop_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/StopExperiment', + request_serializer=experiment.StopExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['stop_experiment'] + + +__all__ = ( + 'ExperimentsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py new file mode 100644 index 00000000..f02dfdbf --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py @@ -0,0 +1,422 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 # type: ignore +from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .grpc import ExperimentsGrpcTransport + + +class ExperimentsGrpcAsyncIOTransport(ExperimentsTransport): + """gRPC AsyncIO backend transport for Experiments. + + Service for managing + [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. + + 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_experiments(self) -> Callable[ + [experiment.ListExperimentsRequest], + Awaitable[experiment.ListExperimentsResponse]]: + r"""Return a callable for the list experiments method over gRPC. + + Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.ListExperimentsRequest], + Awaitable[~.ListExperimentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_experiments' not in self._stubs: + self._stubs['list_experiments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/ListExperiments', + request_serializer=experiment.ListExperimentsRequest.serialize, + response_deserializer=experiment.ListExperimentsResponse.deserialize, + ) + return self._stubs['list_experiments'] + + @property + def get_experiment(self) -> Callable[ + [experiment.GetExperimentRequest], + Awaitable[experiment.Experiment]]: + r"""Return a callable for the get experiment method over gRPC. + + Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.GetExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_experiment' not in self._stubs: + self._stubs['get_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/GetExperiment', + request_serializer=experiment.GetExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['get_experiment'] + + @property + def create_experiment(self) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], + Awaitable[gcdc_experiment.Experiment]]: + r"""Return a callable for the create experiment method over gRPC. + + Creates an + [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the + specified + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + + Returns: + Callable[[~.CreateExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_experiment' not in self._stubs: + self._stubs['create_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/CreateExperiment', + request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['create_experiment'] + + @property + def update_experiment(self) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], + Awaitable[gcdc_experiment.Experiment]]: + r"""Return a callable for the update experiment method over gRPC. + + Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.UpdateExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_experiment' not in self._stubs: + self._stubs['update_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/UpdateExperiment', + request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['update_experiment'] + + @property + def delete_experiment(self) -> Callable[ + [experiment.DeleteExperimentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete experiment method over gRPC. + + Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. + + Returns: + Callable[[~.DeleteExperimentRequest], + 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_experiment' not in self._stubs: + self._stubs['delete_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/DeleteExperiment', + request_serializer=experiment.DeleteExperimentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_experiment'] + + @property + def start_experiment(self) -> Callable[ + [experiment.StartExperimentRequest], + Awaitable[experiment.Experiment]]: + r"""Return a callable for the start experiment method over gRPC. + + Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from PENDING to RUNNING. + + Returns: + Callable[[~.StartExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_experiment' not in self._stubs: + self._stubs['start_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/StartExperiment', + request_serializer=experiment.StartExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['start_experiment'] + + @property + def stop_experiment(self) -> Callable[ + [experiment.StopExperimentRequest], + Awaitable[experiment.Experiment]]: + r"""Return a callable for the stop experiment method over gRPC. + + Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc + only changes the state of experiment from RUNNING to DONE. + + Returns: + Callable[[~.StopExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_experiment' not in self._stubs: + self._stubs['stop_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Experiments/StopExperiment', + request_serializer=experiment.StopExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['stop_experiment'] + + +__all__ = ( + 'ExperimentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__init__.py new file mode 100644 index 00000000..42e3f705 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__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 FlowsClient +from .async_client import FlowsAsyncClient + +__all__ = ( + 'FlowsClient', + 'FlowsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py new file mode 100644 index 00000000..8dcb471b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py @@ -0,0 +1,1008 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.flows import pagers +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import validation_message +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport +from .client import FlowsClient + + +class FlowsAsyncClient: + """Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow].""" + + _client: FlowsClient + + DEFAULT_ENDPOINT = FlowsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FlowsClient.DEFAULT_MTLS_ENDPOINT + + flow_path = staticmethod(FlowsClient.flow_path) + parse_flow_path = staticmethod(FlowsClient.parse_flow_path) + flow_validation_result_path = staticmethod(FlowsClient.flow_validation_result_path) + parse_flow_validation_result_path = staticmethod(FlowsClient.parse_flow_validation_result_path) + intent_path = staticmethod(FlowsClient.intent_path) + parse_intent_path = staticmethod(FlowsClient.parse_intent_path) + page_path = staticmethod(FlowsClient.page_path) + parse_page_path = staticmethod(FlowsClient.parse_page_path) + transition_route_group_path = staticmethod(FlowsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(FlowsClient.parse_transition_route_group_path) + webhook_path = staticmethod(FlowsClient.webhook_path) + parse_webhook_path = staticmethod(FlowsClient.parse_webhook_path) + common_billing_account_path = staticmethod(FlowsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FlowsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FlowsClient.common_folder_path) + parse_common_folder_path = staticmethod(FlowsClient.parse_common_folder_path) + common_organization_path = staticmethod(FlowsClient.common_organization_path) + parse_common_organization_path = staticmethod(FlowsClient.parse_common_organization_path) + common_project_path = staticmethod(FlowsClient.common_project_path) + parse_common_project_path = staticmethod(FlowsClient.parse_common_project_path) + common_location_path = staticmethod(FlowsClient.common_location_path) + parse_common_location_path = staticmethod(FlowsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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: + FlowsAsyncClient: The constructed client. + """ + return FlowsClient.from_service_account_info.__func__(FlowsAsyncClient, 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: + FlowsAsyncClient: The constructed client. + """ + return FlowsClient.from_service_account_file.__func__(FlowsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FlowsTransport: + """Returns the transport used by the client instance. + + Returns: + FlowsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(FlowsClient).get_transport_class, type(FlowsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FlowsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the flows 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, ~.FlowsTransport]): 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 = FlowsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_flow(self, + request: gcdc_flow.CreateFlowRequest = None, + *, + parent: str = None, + flow: gcdc_flow.Flow = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Creates a flow in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateFlowRequest`): + The request object. The request message for + [Flows.CreateFlow][google.cloud.dialogflow.cx.v3.Flows.CreateFlow]. + parent (:class:`str`): + Required. The agent to create a flow for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + flow (:class:`google.cloud.dialogflowcx_v3.types.Flow`): + Required. The flow to create. + This corresponds to the ``flow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, flow]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_flow.CreateFlowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if flow is not None: + request.flow = flow + + # 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_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_flow(self, + request: flow.DeleteFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteFlowRequest`): + The request object. The request message for + [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3.Flows.DeleteFlow]. + name (:class:`str`): + Required. The name of the flow to delete. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = flow.DeleteFlowRequest(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_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_flows(self, + request: flow.ListFlowsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFlowsAsyncPager: + r"""Returns the list of all flows in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListFlowsRequest`): + The request object. The request message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + parent (:class:`str`): + Required. The agent containing the flows. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.flows.pagers.ListFlowsAsyncPager: + The response message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + + 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 = flow.ListFlowsRequest(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_flows, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListFlowsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_flow(self, + request: flow.GetFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.Flow: + r"""Retrieves the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetFlowRequest`): + The request object. The response message for + [Flows.GetFlow][google.cloud.dialogflow.cx.v3.Flows.GetFlow]. + name (:class:`str`): + Required. The name of the flow to get. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = flow.GetFlowRequest(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_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_flow(self, + request: gcdc_flow.UpdateFlowRequest = None, + *, + flow: gcdc_flow.Flow = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Updates the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateFlowRequest`): + The request object. The request message for + [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3.Flows.UpdateFlow]. + flow (:class:`google.cloud.dialogflowcx_v3.types.Flow`): + Required. The flow to update. + This corresponds to the ``flow`` 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 ``update_mask`` is not specified, an error will be + returned. + + 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.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([flow, 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 = gcdc_flow.UpdateFlowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if flow is not None: + request.flow = flow + if update_mask is not None: + 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_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("flow.name", request.flow.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def train_flow(self, + request: flow.TrainFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Trains the specified flow. Note that only the flow in + 'draft' environment is trained. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.TrainFlowRequest`): + The request object. The request message for + [Flows.TrainFlow][google.cloud.dialogflow.cx.v3.Flows.TrainFlow]. + name (:class:`str`): + Required. The flow to train. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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 = flow.TrainFlowRequest(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.train_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def validate_flow(self, + request: flow.ValidateFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ValidateFlowRequest`): + The request object. The request message for + [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3.Flows.ValidateFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + request = flow.ValidateFlowRequest(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.validate_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_flow_validation_result(self, + request: flow.GetFlowValidationResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest`): + The request object. The request message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + name (:class:`str`): + Required. The flow name. Format: + ``projects//locations//agents//flows//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = flow.GetFlowValidationResultRequest(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_flow_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(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_flow(self, + request: flow.ImportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the specified flow to the specified agent + from a binary file. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ImportFlowRequest`): + The request object. The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ImportFlowResponse` + The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + """ + # Create or coerce a protobuf request object. + request = flow.ImportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + flow.ImportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def export_flow(self, + request: flow.ExportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ExportFlowRequest`): + The request object. The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportFlowResponse` + The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + """ + # Create or coerce a protobuf request object. + request = flow.ExportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + flow.ExportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FlowsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py new file mode 100644 index 00000000..9491c46b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py @@ -0,0 +1,1243 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.flows import pagers +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import validation_message +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FlowsGrpcTransport +from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport + + +class FlowsClientMeta(type): + """Metaclass for the Flows 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[FlowsTransport]] + _transport_registry["grpc"] = FlowsGrpcTransport + _transport_registry["grpc_asyncio"] = FlowsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[FlowsTransport]: + """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 FlowsClient(metaclass=FlowsClientMeta): + """Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow].""" + + @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: + FlowsClient: 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: + FlowsClient: 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) -> FlowsTransport: + """Returns the transport used by the client instance. + + Returns: + FlowsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_validation_result_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow_validation_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_validation_result_path(path: str) -> Dict[str,str]: + """Parses a flow_validation_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, FlowsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the flows 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, FlowsTransport]): 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, FlowsTransport): + # transport is a FlowsTransport 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_flow(self, + request: gcdc_flow.CreateFlowRequest = None, + *, + parent: str = None, + flow: gcdc_flow.Flow = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Creates a flow in the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateFlowRequest): + The request object. The request message for + [Flows.CreateFlow][google.cloud.dialogflow.cx.v3.Flows.CreateFlow]. + parent (str): + Required. The agent to create a flow for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + flow (google.cloud.dialogflowcx_v3.types.Flow): + Required. The flow to create. + This corresponds to the ``flow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, flow]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_flow.CreateFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_flow.CreateFlowRequest): + request = gcdc_flow.CreateFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if flow is not None: + request.flow = flow + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_flow(self, + request: flow.DeleteFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a specified flow. + + Args: + request (google.cloud.dialogflowcx_v3.types.DeleteFlowRequest): + The request object. The request message for + [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3.Flows.DeleteFlow]. + name (str): + Required. The name of the flow to delete. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 flow.DeleteFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.DeleteFlowRequest): + request = flow.DeleteFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_flows(self, + request: flow.ListFlowsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFlowsPager: + r"""Returns the list of all flows in the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListFlowsRequest): + The request object. The request message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + parent (str): + Required. The agent containing the flows. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.flows.pagers.ListFlowsPager: + The response message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + + 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 flow.ListFlowsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ListFlowsRequest): + request = flow.ListFlowsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_flows] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListFlowsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_flow(self, + request: flow.GetFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.Flow: + r"""Retrieves the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetFlowRequest): + The request object. The response message for + [Flows.GetFlow][google.cloud.dialogflow.cx.v3.Flows.GetFlow]. + name (str): + Required. The name of the flow to get. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 flow.GetFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.GetFlowRequest): + request = flow.GetFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_flow(self, + request: gcdc_flow.UpdateFlowRequest = None, + *, + flow: gcdc_flow.Flow = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Updates the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateFlowRequest): + The request object. The request message for + [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3.Flows.UpdateFlow]. + flow (google.cloud.dialogflowcx_v3.types.Flow): + Required. The flow to update. + This corresponds to the ``flow`` 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 ``update_mask`` is not specified, an error will be + returned. + + 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.dialogflowcx_v3.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([flow, 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 gcdc_flow.UpdateFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_flow.UpdateFlowRequest): + request = gcdc_flow.UpdateFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if flow is not None: + request.flow = flow + if update_mask is not None: + 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_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("flow.name", request.flow.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def train_flow(self, + request: flow.TrainFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Trains the specified flow. Note that only the flow in + 'draft' environment is trained. + + Args: + request (google.cloud.dialogflowcx_v3.types.TrainFlowRequest): + The request object. The request message for + [Flows.TrainFlow][google.cloud.dialogflow.cx.v3.Flows.TrainFlow]. + name (str): + Required. The flow to train. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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 flow.TrainFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.TrainFlowRequest): + request = flow.TrainFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.train_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def validate_flow(self, + request: flow.ValidateFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Args: + request (google.cloud.dialogflowcx_v3.types.ValidateFlowRequest): + The request object. The request message for + [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3.Flows.ValidateFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ValidateFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ValidateFlowRequest): + request = flow.ValidateFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_flow_validation_result(self, + request: flow.GetFlowValidationResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest): + The request object. The request message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + name (str): + Required. The flow name. Format: + ``projects//locations//agents//flows//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 flow.GetFlowValidationResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.GetFlowValidationResultRequest): + request = flow.GetFlowValidationResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_flow_validation_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_flow(self, + request: flow.ImportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports the specified flow to the specified agent + from a binary file. + + Args: + request (google.cloud.dialogflowcx_v3.types.ImportFlowRequest): + The request object. The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ImportFlowResponse` + The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ImportFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ImportFlowRequest): + request = flow.ImportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + flow.ImportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def export_flow(self, + request: flow.ExportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Args: + request (google.cloud.dialogflowcx_v3.types.ExportFlowRequest): + The request object. The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportFlowResponse` + The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ExportFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ExportFlowRequest): + request = flow.ExportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + flow.ExportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FlowsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/pagers.py new file mode 100644 index 00000000..a9fc8238 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/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.dialogflowcx_v3.types import flow + + +class ListFlowsPager: + """A pager for iterating through ``list_flows`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``flows`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFlows`` requests and continue to iterate + through the ``flows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` + 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[..., flow.ListFlowsResponse], + request: flow.ListFlowsRequest, + response: flow.ListFlowsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListFlowsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListFlowsResponse): + 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 = flow.ListFlowsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[flow.ListFlowsResponse]: + 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[flow.Flow]: + for page in self.pages: + yield from page.flows + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFlowsAsyncPager: + """A pager for iterating through ``list_flows`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``flows`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFlows`` requests and continue to iterate + through the ``flows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` + 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[flow.ListFlowsResponse]], + request: flow.ListFlowsRequest, + response: flow.ListFlowsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListFlowsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListFlowsResponse): + 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 = flow.ListFlowsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[flow.ListFlowsResponse]: + 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[flow.Flow]: + async def async_generator(): + async for page in self.pages: + for response in page.flows: + 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/v3/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py new file mode 100644 index 00000000..4ba28aff --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/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 FlowsTransport +from .grpc import FlowsGrpcTransport +from .grpc_asyncio import FlowsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FlowsTransport]] +_transport_registry['grpc'] = FlowsGrpcTransport +_transport_registry['grpc_asyncio'] = FlowsGrpcAsyncIOTransport + +__all__ = ( + 'FlowsTransport', + 'FlowsGrpcTransport', + 'FlowsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/base.py new file mode 100644 index 00000000..c7ac3fb3 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/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.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +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-dialogflowcx', + ).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 FlowsTransport(abc.ABC): + """Abstract transport class for Flows.""" + + 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_flow: gapic_v1.method.wrap_method( + self.create_flow, + default_timeout=None, + client_info=client_info, + ), + self.delete_flow: gapic_v1.method.wrap_method( + self.delete_flow, + default_timeout=None, + client_info=client_info, + ), + self.list_flows: gapic_v1.method.wrap_method( + self.list_flows, + default_timeout=None, + client_info=client_info, + ), + self.get_flow: gapic_v1.method.wrap_method( + self.get_flow, + default_timeout=None, + client_info=client_info, + ), + self.update_flow: gapic_v1.method.wrap_method( + self.update_flow, + default_timeout=None, + client_info=client_info, + ), + self.train_flow: gapic_v1.method.wrap_method( + self.train_flow, + default_timeout=None, + client_info=client_info, + ), + self.validate_flow: gapic_v1.method.wrap_method( + self.validate_flow, + default_timeout=None, + client_info=client_info, + ), + self.get_flow_validation_result: gapic_v1.method.wrap_method( + self.get_flow_validation_result, + default_timeout=None, + client_info=client_info, + ), + self.import_flow: gapic_v1.method.wrap_method( + self.import_flow, + default_timeout=None, + client_info=client_info, + ), + self.export_flow: gapic_v1.method.wrap_method( + self.export_flow, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_flow(self) -> Callable[ + [gcdc_flow.CreateFlowRequest], + Union[ + gcdc_flow.Flow, + Awaitable[gcdc_flow.Flow] + ]]: + raise NotImplementedError() + + @property + def delete_flow(self) -> Callable[ + [flow.DeleteFlowRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_flows(self) -> Callable[ + [flow.ListFlowsRequest], + Union[ + flow.ListFlowsResponse, + Awaitable[flow.ListFlowsResponse] + ]]: + raise NotImplementedError() + + @property + def get_flow(self) -> Callable[ + [flow.GetFlowRequest], + Union[ + flow.Flow, + Awaitable[flow.Flow] + ]]: + raise NotImplementedError() + + @property + def update_flow(self) -> Callable[ + [gcdc_flow.UpdateFlowRequest], + Union[ + gcdc_flow.Flow, + Awaitable[gcdc_flow.Flow] + ]]: + raise NotImplementedError() + + @property + def train_flow(self) -> Callable[ + [flow.TrainFlowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def validate_flow(self) -> Callable[ + [flow.ValidateFlowRequest], + Union[ + flow.FlowValidationResult, + Awaitable[flow.FlowValidationResult] + ]]: + raise NotImplementedError() + + @property + def get_flow_validation_result(self) -> Callable[ + [flow.GetFlowValidationResultRequest], + Union[ + flow.FlowValidationResult, + Awaitable[flow.FlowValidationResult] + ]]: + raise NotImplementedError() + + @property + def import_flow(self) -> Callable[ + [flow.ImportFlowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_flow(self) -> Callable[ + [flow.ExportFlowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'FlowsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py new file mode 100644 index 00000000..45af79c4 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py @@ -0,0 +1,511 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import FlowsTransport, DEFAULT_CLIENT_INFO + + +class FlowsGrpcTransport(FlowsTransport): + """gRPC backend transport for Flows. + + Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow]. + + 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 create_flow(self) -> Callable[ + [gcdc_flow.CreateFlowRequest], + gcdc_flow.Flow]: + r"""Return a callable for the create flow method over gRPC. + + Creates a flow in the specified agent. + + Returns: + Callable[[~.CreateFlowRequest], + ~.Flow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_flow' not in self._stubs: + self._stubs['create_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/CreateFlow', + request_serializer=gcdc_flow.CreateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['create_flow'] + + @property + def delete_flow(self) -> Callable[ + [flow.DeleteFlowRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete flow method over gRPC. + + Deletes a specified flow. + + Returns: + Callable[[~.DeleteFlowRequest], + ~.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_flow' not in self._stubs: + self._stubs['delete_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/DeleteFlow', + request_serializer=flow.DeleteFlowRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_flow'] + + @property + def list_flows(self) -> Callable[ + [flow.ListFlowsRequest], + flow.ListFlowsResponse]: + r"""Return a callable for the list flows method over gRPC. + + Returns the list of all flows in the specified agent. + + Returns: + Callable[[~.ListFlowsRequest], + ~.ListFlowsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_flows' not in self._stubs: + self._stubs['list_flows'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ListFlows', + request_serializer=flow.ListFlowsRequest.serialize, + response_deserializer=flow.ListFlowsResponse.deserialize, + ) + return self._stubs['list_flows'] + + @property + def get_flow(self) -> Callable[ + [flow.GetFlowRequest], + flow.Flow]: + r"""Return a callable for the get flow method over gRPC. + + Retrieves the specified flow. + + Returns: + Callable[[~.GetFlowRequest], + ~.Flow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow' not in self._stubs: + self._stubs['get_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/GetFlow', + request_serializer=flow.GetFlowRequest.serialize, + response_deserializer=flow.Flow.deserialize, + ) + return self._stubs['get_flow'] + + @property + def update_flow(self) -> Callable[ + [gcdc_flow.UpdateFlowRequest], + gcdc_flow.Flow]: + r"""Return a callable for the update flow method over gRPC. + + Updates the specified flow. + + Returns: + Callable[[~.UpdateFlowRequest], + ~.Flow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_flow' not in self._stubs: + self._stubs['update_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/UpdateFlow', + request_serializer=gcdc_flow.UpdateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['update_flow'] + + @property + def train_flow(self) -> Callable[ + [flow.TrainFlowRequest], + operations_pb2.Operation]: + r"""Return a callable for the train flow method over gRPC. + + Trains the specified flow. Note that only the flow in + 'draft' environment is trained. + + Returns: + Callable[[~.TrainFlowRequest], + ~.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_flow' not in self._stubs: + self._stubs['train_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/TrainFlow', + request_serializer=flow.TrainFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['train_flow'] + + @property + def validate_flow(self) -> Callable[ + [flow.ValidateFlowRequest], + flow.FlowValidationResult]: + r"""Return a callable for the validate flow method over gRPC. + + Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Returns: + Callable[[~.ValidateFlowRequest], + ~.FlowValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_flow' not in self._stubs: + self._stubs['validate_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ValidateFlow', + request_serializer=flow.ValidateFlowRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['validate_flow'] + + @property + def get_flow_validation_result(self) -> Callable[ + [flow.GetFlowValidationResultRequest], + flow.FlowValidationResult]: + r"""Return a callable for the get flow validation result method over gRPC. + + Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Returns: + Callable[[~.GetFlowValidationResultRequest], + ~.FlowValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow_validation_result' not in self._stubs: + self._stubs['get_flow_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/GetFlowValidationResult', + request_serializer=flow.GetFlowValidationResultRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['get_flow_validation_result'] + + @property + def import_flow(self) -> Callable[ + [flow.ImportFlowRequest], + operations_pb2.Operation]: + r"""Return a callable for the import flow method over gRPC. + + Imports the specified flow to the specified agent + from a binary file. + + Returns: + Callable[[~.ImportFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_flow' not in self._stubs: + self._stubs['import_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ImportFlow', + request_serializer=flow.ImportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_flow'] + + @property + def export_flow(self) -> Callable[ + [flow.ExportFlowRequest], + operations_pb2.Operation]: + r"""Return a callable for the export flow method over gRPC. + + Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Returns: + Callable[[~.ExportFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_flow' not in self._stubs: + self._stubs['export_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ExportFlow', + request_serializer=flow.ExportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_flow'] + + +__all__ = ( + 'FlowsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py new file mode 100644 index 00000000..05379556 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py @@ -0,0 +1,515 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import FlowsTransport, DEFAULT_CLIENT_INFO +from .grpc import FlowsGrpcTransport + + +class FlowsGrpcAsyncIOTransport(FlowsTransport): + """gRPC AsyncIO backend transport for Flows. + + Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow]. + + 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 create_flow(self) -> Callable[ + [gcdc_flow.CreateFlowRequest], + Awaitable[gcdc_flow.Flow]]: + r"""Return a callable for the create flow method over gRPC. + + Creates a flow in the specified agent. + + Returns: + Callable[[~.CreateFlowRequest], + Awaitable[~.Flow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_flow' not in self._stubs: + self._stubs['create_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/CreateFlow', + request_serializer=gcdc_flow.CreateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['create_flow'] + + @property + def delete_flow(self) -> Callable[ + [flow.DeleteFlowRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete flow method over gRPC. + + Deletes a specified flow. + + Returns: + Callable[[~.DeleteFlowRequest], + 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_flow' not in self._stubs: + self._stubs['delete_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/DeleteFlow', + request_serializer=flow.DeleteFlowRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_flow'] + + @property + def list_flows(self) -> Callable[ + [flow.ListFlowsRequest], + Awaitable[flow.ListFlowsResponse]]: + r"""Return a callable for the list flows method over gRPC. + + Returns the list of all flows in the specified agent. + + Returns: + Callable[[~.ListFlowsRequest], + Awaitable[~.ListFlowsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_flows' not in self._stubs: + self._stubs['list_flows'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ListFlows', + request_serializer=flow.ListFlowsRequest.serialize, + response_deserializer=flow.ListFlowsResponse.deserialize, + ) + return self._stubs['list_flows'] + + @property + def get_flow(self) -> Callable[ + [flow.GetFlowRequest], + Awaitable[flow.Flow]]: + r"""Return a callable for the get flow method over gRPC. + + Retrieves the specified flow. + + Returns: + Callable[[~.GetFlowRequest], + Awaitable[~.Flow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow' not in self._stubs: + self._stubs['get_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/GetFlow', + request_serializer=flow.GetFlowRequest.serialize, + response_deserializer=flow.Flow.deserialize, + ) + return self._stubs['get_flow'] + + @property + def update_flow(self) -> Callable[ + [gcdc_flow.UpdateFlowRequest], + Awaitable[gcdc_flow.Flow]]: + r"""Return a callable for the update flow method over gRPC. + + Updates the specified flow. + + Returns: + Callable[[~.UpdateFlowRequest], + Awaitable[~.Flow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_flow' not in self._stubs: + self._stubs['update_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/UpdateFlow', + request_serializer=gcdc_flow.UpdateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['update_flow'] + + @property + def train_flow(self) -> Callable[ + [flow.TrainFlowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the train flow method over gRPC. + + Trains the specified flow. Note that only the flow in + 'draft' environment is trained. + + Returns: + Callable[[~.TrainFlowRequest], + 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_flow' not in self._stubs: + self._stubs['train_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/TrainFlow', + request_serializer=flow.TrainFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['train_flow'] + + @property + def validate_flow(self) -> Callable[ + [flow.ValidateFlowRequest], + Awaitable[flow.FlowValidationResult]]: + r"""Return a callable for the validate flow method over gRPC. + + Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Returns: + Callable[[~.ValidateFlowRequest], + Awaitable[~.FlowValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_flow' not in self._stubs: + self._stubs['validate_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ValidateFlow', + request_serializer=flow.ValidateFlowRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['validate_flow'] + + @property + def get_flow_validation_result(self) -> Callable[ + [flow.GetFlowValidationResultRequest], + Awaitable[flow.FlowValidationResult]]: + r"""Return a callable for the get flow validation result method over gRPC. + + Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Returns: + Callable[[~.GetFlowValidationResultRequest], + Awaitable[~.FlowValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow_validation_result' not in self._stubs: + self._stubs['get_flow_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/GetFlowValidationResult', + request_serializer=flow.GetFlowValidationResultRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['get_flow_validation_result'] + + @property + def import_flow(self) -> Callable[ + [flow.ImportFlowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import flow method over gRPC. + + Imports the specified flow to the specified agent + from a binary file. + + Returns: + Callable[[~.ImportFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_flow' not in self._stubs: + self._stubs['import_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ImportFlow', + request_serializer=flow.ImportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_flow'] + + @property + def export_flow(self) -> Callable[ + [flow.ExportFlowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export flow method over gRPC. + + Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Returns: + Callable[[~.ExportFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_flow' not in self._stubs: + self._stubs['export_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Flows/ExportFlow', + request_serializer=flow.ExportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_flow'] + + +__all__ = ( + 'FlowsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/__init__.py new file mode 100644 index 00000000..8204500f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py new file mode 100644 index 00000000..0c7cd7e0 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py @@ -0,0 +1,580 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.intents import pagers +from google.cloud.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +from google.protobuf import field_mask_pb2 # 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.cx.v3.Intent]. + """ + + _client: IntentsClient + + DEFAULT_ENDPOINT = IntentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = IntentsClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(IntentsClient.entity_type_path) + parse_entity_type_path = staticmethod(IntentsClient.parse_entity_type_path) + intent_path = staticmethod(IntentsClient.intent_path) + parse_intent_path = staticmethod(IntentsClient.parse_intent_path) + common_billing_account_path = staticmethod(IntentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(IntentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(IntentsClient.common_folder_path) + parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) + common_organization_path = staticmethod(IntentsClient.common_organization_path) + parse_common_organization_path = staticmethod(IntentsClient.parse_common_organization_path) + common_project_path = staticmethod(IntentsClient.common_project_path) + parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) + common_location_path = staticmethod(IntentsClient.common_location_path) + parse_common_location_path = staticmethod(IntentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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, + 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.dialogflowcx_v3.types.ListIntentsRequest`): + The request object. The request message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. + parent (:class:`str`): + Required. The agent to list all intents for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.intents.pagers.ListIntentsAsyncPager: + The response message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.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]) + if request is not 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 + + # 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, + 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.dialogflowcx_v3.types.GetIntentRequest`): + The request object. The request message for + [Intents.GetIntent][google.cloud.dialogflow.cx.v3.Intents.GetIntent]. + name (:class:`str`): + Required. The name of the intent. Format: + ``projects//locations//agents//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. + + Returns: + google.cloud.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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.GetIntentRequest(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_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: gcdc_intent.CreateIntentRequest = None, + *, + parent: str = None, + intent: gcdc_intent.Intent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Creates an intent in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateIntentRequest`): + The request object. The request message for + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent]. + parent (:class:`str`): + Required. The agent to create an intent for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent (:class:`google.cloud.dialogflowcx_v3.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. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_intent.CreateIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent is not None: + request.intent = intent + + # 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: gcdc_intent.UpdateIntentRequest = None, + *, + intent: gcdc_intent.Intent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Updates the specified intent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateIntentRequest`): + The request object. The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent]. + intent (:class:`google.cloud.dialogflowcx_v3.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`): + 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.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity 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]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_intent.UpdateIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intent is not None: + request.intent = intent + if update_mask is not None: + 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. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteIntentRequest`): + The request object. The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3.Intents.DeleteIntent]. + name (:class:`str`): + Required. The name of the intent to delete. Format: + ``projects//locations//agents//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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "IntentsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py new file mode 100644 index 00000000..364a8eae --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py @@ -0,0 +1,776 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.intents import pagers +from google.cloud.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +from google.protobuf import field_mask_pb2 # 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.cx.v3.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 entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/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, + 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.dialogflowcx_v3.types.ListIntentsRequest): + The request object. The request message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. + parent (str): + Required. The agent to list all intents for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.intents.pagers.ListIntentsPager: + The response message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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 + + # 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, + 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.dialogflowcx_v3.types.GetIntentRequest): + The request object. The request message for + [Intents.GetIntent][google.cloud.dialogflow.cx.v3.Intents.GetIntent]. + name (str): + Required. The name of the intent. Format: + ``projects//locations//agents//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. + + Returns: + google.cloud.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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.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 + + # 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: gcdc_intent.CreateIntentRequest = None, + *, + parent: str = None, + intent: gcdc_intent.Intent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Creates an intent in the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateIntentRequest): + The request object. The request message for + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent]. + parent (str): + Required. The agent to create an intent for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent (google.cloud.dialogflowcx_v3.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. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_intent.CreateIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_intent.CreateIntentRequest): + request = gcdc_intent.CreateIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent is not None: + request.intent = intent + + # 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: gcdc_intent.UpdateIntentRequest = None, + *, + intent: gcdc_intent.Intent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Updates the specified intent. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateIntentRequest): + The request object. The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent]. + intent (google.cloud.dialogflowcx_v3.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): + 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.dialogflowcx_v3.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_intent.UpdateIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_intent.UpdateIntentRequest): + request = gcdc_intent.UpdateIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intent is not None: + request.intent = intent + if update_mask is not None: + 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. + + Args: + request (google.cloud.dialogflowcx_v3.types.DeleteIntentRequest): + The request object. The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3.Intents.DeleteIntent]. + name (str): + Required. The name of the intent to delete. Format: + ``projects//locations//agents//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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "IntentsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/pagers.py new file mode 100644 index 00000000..8883d7c0 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import intent + + +class ListIntentsPager: + """A pager for iterating through ``list_intents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListIntentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListIntentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.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/v3/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py new file mode 100644 index 00000000..aa8039bb --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/intents/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/base.py new file mode 100644 index 00000000..02323468 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/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.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +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-dialogflowcx', + ).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, + ), + } + + @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[ + [gcdc_intent.CreateIntentRequest], + Union[ + gcdc_intent.Intent, + Awaitable[gcdc_intent.Intent] + ]]: + raise NotImplementedError() + + @property + def update_intent(self) -> Callable[ + [gcdc_intent.UpdateIntentRequest], + Union[ + gcdc_intent.Intent, + Awaitable[gcdc_intent.Intent] + ]]: + raise NotImplementedError() + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'IntentsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py new file mode 100644 index 00000000..3a2e0b75 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/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.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +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.cx.v3.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] = {} + + 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_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.cx.v3.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.cx.v3.Intents/GetIntent', + request_serializer=intent.GetIntentRequest.serialize, + response_deserializer=intent.Intent.deserialize, + ) + return self._stubs['get_intent'] + + @property + def create_intent(self) -> Callable[ + [gcdc_intent.CreateIntentRequest], + gcdc_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.cx.v3.Intents/CreateIntent', + request_serializer=gcdc_intent.CreateIntentRequest.serialize, + response_deserializer=gcdc_intent.Intent.deserialize, + ) + return self._stubs['create_intent'] + + @property + def update_intent(self) -> Callable[ + [gcdc_intent.UpdateIntentRequest], + gcdc_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.cx.v3.Intents/UpdateIntent', + request_serializer=gcdc_intent.UpdateIntentRequest.serialize, + response_deserializer=gcdc_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. + + 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.cx.v3.Intents/DeleteIntent', + request_serializer=intent.DeleteIntentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_intent'] + + +__all__ = ( + 'IntentsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py new file mode 100644 index 00000000..ca672c54 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/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.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +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.cx.v3.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] = {} + + 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_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.cx.v3.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.cx.v3.Intents/GetIntent', + request_serializer=intent.GetIntentRequest.serialize, + response_deserializer=intent.Intent.deserialize, + ) + return self._stubs['get_intent'] + + @property + def create_intent(self) -> Callable[ + [gcdc_intent.CreateIntentRequest], + Awaitable[gcdc_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.cx.v3.Intents/CreateIntent', + request_serializer=gcdc_intent.CreateIntentRequest.serialize, + response_deserializer=gcdc_intent.Intent.deserialize, + ) + return self._stubs['create_intent'] + + @property + def update_intent(self) -> Callable[ + [gcdc_intent.UpdateIntentRequest], + Awaitable[gcdc_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.cx.v3.Intents/UpdateIntent', + request_serializer=gcdc_intent.UpdateIntentRequest.serialize, + response_deserializer=gcdc_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. + + 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.cx.v3.Intents/DeleteIntent', + request_serializer=intent.DeleteIntentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_intent'] + + +__all__ = ( + 'IntentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__init__.py new file mode 100644 index 00000000..b8668f72 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__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 PagesClient +from .async_client import PagesAsyncClient + +__all__ = ( + 'PagesClient', + 'PagesAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py new file mode 100644 index 00000000..e004686a --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py @@ -0,0 +1,631 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.pages import pagers +from google.cloud.dialogflowcx_v3.types import fulfillment +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport +from .client import PagesClient + + +class PagesAsyncClient: + """Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page].""" + + _client: PagesClient + + DEFAULT_ENDPOINT = PagesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PagesClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(PagesClient.entity_type_path) + parse_entity_type_path = staticmethod(PagesClient.parse_entity_type_path) + flow_path = staticmethod(PagesClient.flow_path) + parse_flow_path = staticmethod(PagesClient.parse_flow_path) + intent_path = staticmethod(PagesClient.intent_path) + parse_intent_path = staticmethod(PagesClient.parse_intent_path) + page_path = staticmethod(PagesClient.page_path) + parse_page_path = staticmethod(PagesClient.parse_page_path) + transition_route_group_path = staticmethod(PagesClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(PagesClient.parse_transition_route_group_path) + webhook_path = staticmethod(PagesClient.webhook_path) + parse_webhook_path = staticmethod(PagesClient.parse_webhook_path) + common_billing_account_path = staticmethod(PagesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PagesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PagesClient.common_folder_path) + parse_common_folder_path = staticmethod(PagesClient.parse_common_folder_path) + common_organization_path = staticmethod(PagesClient.common_organization_path) + parse_common_organization_path = staticmethod(PagesClient.parse_common_organization_path) + common_project_path = staticmethod(PagesClient.common_project_path) + parse_common_project_path = staticmethod(PagesClient.parse_common_project_path) + common_location_path = staticmethod(PagesClient.common_location_path) + parse_common_location_path = staticmethod(PagesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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: + PagesAsyncClient: The constructed client. + """ + return PagesClient.from_service_account_info.__func__(PagesAsyncClient, 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: + PagesAsyncClient: The constructed client. + """ + return PagesClient.from_service_account_file.__func__(PagesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PagesTransport: + """Returns the transport used by the client instance. + + Returns: + PagesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PagesClient).get_transport_class, type(PagesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PagesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the pages 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, ~.PagesTransport]): 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 = PagesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_pages(self, + request: page.ListPagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPagesAsyncPager: + r"""Returns the list of all pages in the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListPagesRequest`): + The request object. The request message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + parent (:class:`str`): + Required. The flow to list all pages for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.pages.pagers.ListPagesAsyncPager: + The response message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + + 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 = page.ListPagesRequest(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_pages, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListPagesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_page(self, + request: page.GetPageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> page.Page: + r"""Retrieves the specified page. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetPageRequest`): + The request object. The request message for + [Pages.GetPage][google.cloud.dialogflow.cx.v3.Pages.GetPage]. + name (:class:`str`): + Required. The name of the page. Format: + ``projects//locations//agents//flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = page.GetPageRequest(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_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_page(self, + request: gcdc_page.CreatePageRequest = None, + *, + parent: str = None, + page: gcdc_page.Page = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Creates a page in the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreatePageRequest`): + The request object. The request message for + [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage]. + parent (:class:`str`): + Required. The flow to create a page for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + page (:class:`google.cloud.dialogflowcx_v3.types.Page`): + Required. The page to create. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, page]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_page.CreatePageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if page is not None: + request.page = page + + # 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_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_page(self, + request: gcdc_page.UpdatePageRequest = None, + *, + page: gcdc_page.Page = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Updates the specified page. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdatePageRequest`): + The request object. The request message for + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage]. + page (:class:`google.cloud.dialogflowcx_v3.types.Page`): + Required. The page to update. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([page, 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 = gcdc_page.UpdatePageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if page is not None: + request.page = page + if update_mask is not None: + 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_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("page.name", request.page.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_page(self, + request: page.DeletePageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified page. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeletePageRequest`): + The request object. The request message for + [Pages.DeletePage][google.cloud.dialogflow.cx.v3.Pages.DeletePage]. + name (:class:`str`): + Required. The name of the page to delete. Format: + ``projects//locations//agents//Flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = page.DeletePageRequest(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_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PagesAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py new file mode 100644 index 00000000..43b5da5c --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py @@ -0,0 +1,863 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.pages import pagers +from google.cloud.dialogflowcx_v3.types import fulfillment +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PagesGrpcTransport +from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport + + +class PagesClientMeta(type): + """Metaclass for the Pages 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[PagesTransport]] + _transport_registry["grpc"] = PagesGrpcTransport + _transport_registry["grpc_asyncio"] = PagesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PagesTransport]: + """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 PagesClient(metaclass=PagesClientMeta): + """Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page].""" + + @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: + PagesClient: 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: + PagesClient: 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) -> PagesTransport: + """Returns the transport used by the client instance. + + Returns: + PagesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, PagesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the pages 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, PagesTransport]): 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, PagesTransport): + # transport is a PagesTransport 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_pages(self, + request: page.ListPagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPagesPager: + r"""Returns the list of all pages in the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListPagesRequest): + The request object. The request message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + parent (str): + Required. The flow to list all pages for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.pages.pagers.ListPagesPager: + The response message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + + 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 page.ListPagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, page.ListPagesRequest): + request = page.ListPagesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_pages] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListPagesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_page(self, + request: page.GetPageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> page.Page: + r"""Retrieves the specified page. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetPageRequest): + The request object. The request message for + [Pages.GetPage][google.cloud.dialogflow.cx.v3.Pages.GetPage]. + name (str): + Required. The name of the page. Format: + ``projects//locations//agents//flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 page.GetPageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, page.GetPageRequest): + request = page.GetPageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_page] + + # Certain fields should be provided 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_page(self, + request: gcdc_page.CreatePageRequest = None, + *, + parent: str = None, + page: gcdc_page.Page = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Creates a page in the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreatePageRequest): + The request object. The request message for + [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage]. + parent (str): + Required. The flow to create a page for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + page (google.cloud.dialogflowcx_v3.types.Page): + Required. The page to create. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, page]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_page.CreatePageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_page.CreatePageRequest): + request = gcdc_page.CreatePageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if page is not None: + request.page = page + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_page] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_page(self, + request: gcdc_page.UpdatePageRequest = None, + *, + page: gcdc_page.Page = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Updates the specified page. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdatePageRequest): + The request object. The request message for + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage]. + page (google.cloud.dialogflowcx_v3.types.Page): + Required. The page to update. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.dialogflowcx_v3.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([page, 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 gcdc_page.UpdatePageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_page.UpdatePageRequest): + request = gcdc_page.UpdatePageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if page is not None: + request.page = page + if update_mask is not None: + 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_page] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("page.name", request.page.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_page(self, + request: page.DeletePageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified page. + + Args: + request (google.cloud.dialogflowcx_v3.types.DeletePageRequest): + The request object. The request message for + [Pages.DeletePage][google.cloud.dialogflow.cx.v3.Pages.DeletePage]. + name (str): + Required. The name of the page to delete. Format: + ``projects//locations//agents//Flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 page.DeletePageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, page.DeletePageRequest): + request = page.DeletePageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_page] + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PagesClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/pagers.py new file mode 100644 index 00000000..fb23ff83 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/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.dialogflowcx_v3.types import page + + +class ListPagesPager: + """A pager for iterating through ``list_pages`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``pages`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPages`` requests and continue to iterate + through the ``pages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` + 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[..., page.ListPagesResponse], + request: page.ListPagesRequest, + response: page.ListPagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListPagesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListPagesResponse): + 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 = page.ListPagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[page.ListPagesResponse]: + 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[page.Page]: + for page in self.pages: + yield from page.pages + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPagesAsyncPager: + """A pager for iterating through ``list_pages`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``pages`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPages`` requests and continue to iterate + through the ``pages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` + 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[page.ListPagesResponse]], + request: page.ListPagesRequest, + response: page.ListPagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListPagesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListPagesResponse): + 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 = page.ListPagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[page.ListPagesResponse]: + 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[page.Page]: + async def async_generator(): + async for page in self.pages: + for response in page.pages: + 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/v3/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py new file mode 100644 index 00000000..ee74f029 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/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 PagesTransport +from .grpc import PagesGrpcTransport +from .grpc_asyncio import PagesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PagesTransport]] +_transport_registry['grpc'] = PagesGrpcTransport +_transport_registry['grpc_asyncio'] = PagesGrpcAsyncIOTransport + +__all__ = ( + 'PagesTransport', + 'PagesGrpcTransport', + 'PagesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/base.py new file mode 100644 index 00000000..f141931d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/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.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +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-dialogflowcx', + ).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 PagesTransport(abc.ABC): + """Abstract transport class for Pages.""" + + 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_pages: gapic_v1.method.wrap_method( + self.list_pages, + default_timeout=None, + client_info=client_info, + ), + self.get_page: gapic_v1.method.wrap_method( + self.get_page, + default_timeout=None, + client_info=client_info, + ), + self.create_page: gapic_v1.method.wrap_method( + self.create_page, + default_timeout=None, + client_info=client_info, + ), + self.update_page: gapic_v1.method.wrap_method( + self.update_page, + default_timeout=None, + client_info=client_info, + ), + self.delete_page: gapic_v1.method.wrap_method( + self.delete_page, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_pages(self) -> Callable[ + [page.ListPagesRequest], + Union[ + page.ListPagesResponse, + Awaitable[page.ListPagesResponse] + ]]: + raise NotImplementedError() + + @property + def get_page(self) -> Callable[ + [page.GetPageRequest], + Union[ + page.Page, + Awaitable[page.Page] + ]]: + raise NotImplementedError() + + @property + def create_page(self) -> Callable[ + [gcdc_page.CreatePageRequest], + Union[ + gcdc_page.Page, + Awaitable[gcdc_page.Page] + ]]: + raise NotImplementedError() + + @property + def update_page(self) -> Callable[ + [gcdc_page.UpdatePageRequest], + Union[ + gcdc_page.Page, + Awaitable[gcdc_page.Page] + ]]: + raise NotImplementedError() + + @property + def delete_page(self) -> Callable[ + [page.DeletePageRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'PagesTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py new file mode 100644 index 00000000..a0448cdd --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py @@ -0,0 +1,354 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.protobuf import empty_pb2 # type: ignore +from .base import PagesTransport, DEFAULT_CLIENT_INFO + + +class PagesGrpcTransport(PagesTransport): + """gRPC backend transport for Pages. + + Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page]. + + 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_pages(self) -> Callable[ + [page.ListPagesRequest], + page.ListPagesResponse]: + r"""Return a callable for the list pages method over gRPC. + + Returns the list of all pages in the specified flow. + + Returns: + Callable[[~.ListPagesRequest], + ~.ListPagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_pages' not in self._stubs: + self._stubs['list_pages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/ListPages', + request_serializer=page.ListPagesRequest.serialize, + response_deserializer=page.ListPagesResponse.deserialize, + ) + return self._stubs['list_pages'] + + @property + def get_page(self) -> Callable[ + [page.GetPageRequest], + page.Page]: + r"""Return a callable for the get page method over gRPC. + + Retrieves the specified page. + + Returns: + Callable[[~.GetPageRequest], + ~.Page]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_page' not in self._stubs: + self._stubs['get_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/GetPage', + request_serializer=page.GetPageRequest.serialize, + response_deserializer=page.Page.deserialize, + ) + return self._stubs['get_page'] + + @property + def create_page(self) -> Callable[ + [gcdc_page.CreatePageRequest], + gcdc_page.Page]: + r"""Return a callable for the create page method over gRPC. + + Creates a page in the specified flow. + + Returns: + Callable[[~.CreatePageRequest], + ~.Page]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_page' not in self._stubs: + self._stubs['create_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/CreatePage', + request_serializer=gcdc_page.CreatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['create_page'] + + @property + def update_page(self) -> Callable[ + [gcdc_page.UpdatePageRequest], + gcdc_page.Page]: + r"""Return a callable for the update page method over gRPC. + + Updates the specified page. + + Returns: + Callable[[~.UpdatePageRequest], + ~.Page]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_page' not in self._stubs: + self._stubs['update_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/UpdatePage', + request_serializer=gcdc_page.UpdatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['update_page'] + + @property + def delete_page(self) -> Callable[ + [page.DeletePageRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete page method over gRPC. + + Deletes the specified page. + + Returns: + Callable[[~.DeletePageRequest], + ~.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_page' not in self._stubs: + self._stubs['delete_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/DeletePage', + request_serializer=page.DeletePageRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_page'] + + +__all__ = ( + 'PagesGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py new file mode 100644 index 00000000..4892a267 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py @@ -0,0 +1,358 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.protobuf import empty_pb2 # type: ignore +from .base import PagesTransport, DEFAULT_CLIENT_INFO +from .grpc import PagesGrpcTransport + + +class PagesGrpcAsyncIOTransport(PagesTransport): + """gRPC AsyncIO backend transport for Pages. + + Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page]. + + 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_pages(self) -> Callable[ + [page.ListPagesRequest], + Awaitable[page.ListPagesResponse]]: + r"""Return a callable for the list pages method over gRPC. + + Returns the list of all pages in the specified flow. + + Returns: + Callable[[~.ListPagesRequest], + Awaitable[~.ListPagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_pages' not in self._stubs: + self._stubs['list_pages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/ListPages', + request_serializer=page.ListPagesRequest.serialize, + response_deserializer=page.ListPagesResponse.deserialize, + ) + return self._stubs['list_pages'] + + @property + def get_page(self) -> Callable[ + [page.GetPageRequest], + Awaitable[page.Page]]: + r"""Return a callable for the get page method over gRPC. + + Retrieves the specified page. + + Returns: + Callable[[~.GetPageRequest], + Awaitable[~.Page]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_page' not in self._stubs: + self._stubs['get_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/GetPage', + request_serializer=page.GetPageRequest.serialize, + response_deserializer=page.Page.deserialize, + ) + return self._stubs['get_page'] + + @property + def create_page(self) -> Callable[ + [gcdc_page.CreatePageRequest], + Awaitable[gcdc_page.Page]]: + r"""Return a callable for the create page method over gRPC. + + Creates a page in the specified flow. + + Returns: + Callable[[~.CreatePageRequest], + Awaitable[~.Page]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_page' not in self._stubs: + self._stubs['create_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/CreatePage', + request_serializer=gcdc_page.CreatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['create_page'] + + @property + def update_page(self) -> Callable[ + [gcdc_page.UpdatePageRequest], + Awaitable[gcdc_page.Page]]: + r"""Return a callable for the update page method over gRPC. + + Updates the specified page. + + Returns: + Callable[[~.UpdatePageRequest], + Awaitable[~.Page]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_page' not in self._stubs: + self._stubs['update_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/UpdatePage', + request_serializer=gcdc_page.UpdatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['update_page'] + + @property + def delete_page(self) -> Callable[ + [page.DeletePageRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete page method over gRPC. + + Deletes the specified page. + + Returns: + Callable[[~.DeletePageRequest], + 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_page' not in self._stubs: + self._stubs['delete_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Pages/DeletePage', + request_serializer=page.DeletePageRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_page'] + + +__all__ = ( + 'PagesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py new file mode 100644 index 00000000..292d96e7 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__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 SecuritySettingsServiceClient +from .async_client import SecuritySettingsServiceAsyncClient + +__all__ = ( + 'SecuritySettingsServiceClient', + 'SecuritySettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py new file mode 100644 index 00000000..54b7d269 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.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. +# +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.dialogflowcx_v3.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport +from .client import SecuritySettingsServiceClient + + +class SecuritySettingsServiceAsyncClient: + """Service for managing security settings for Dialogflow.""" + + _client: SecuritySettingsServiceClient + + DEFAULT_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_MTLS_ENDPOINT + + security_settings_path = staticmethod(SecuritySettingsServiceClient.security_settings_path) + parse_security_settings_path = staticmethod(SecuritySettingsServiceClient.parse_security_settings_path) + common_billing_account_path = staticmethod(SecuritySettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecuritySettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecuritySettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SecuritySettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SecuritySettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SecuritySettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SecuritySettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(SecuritySettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(SecuritySettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(SecuritySettingsServiceClient.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: + SecuritySettingsServiceAsyncClient: The constructed client. + """ + return SecuritySettingsServiceClient.from_service_account_info.__func__(SecuritySettingsServiceAsyncClient, 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: + SecuritySettingsServiceAsyncClient: The constructed client. + """ + return SecuritySettingsServiceClient.from_service_account_file.__func__(SecuritySettingsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SecuritySettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SecuritySettingsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SecuritySettingsServiceClient).get_transport_class, type(SecuritySettingsServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SecuritySettingsServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security settings service 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, ~.SecuritySettingsServiceTransport]): 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 = SecuritySettingsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_security_settings(self, + request: gcdc_security_settings.CreateSecuritySettingsRequest = None, + *, + parent: str = None, + security_settings: gcdc_security_settings.SecuritySettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Create security settings in the specified location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.CreateSecuritySettings][]. + parent (:class:`str`): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_settings (:class:`google.cloud.dialogflowcx_v3.types.SecuritySettings`): + Required. The security settings to + create. + + This corresponds to the ``security_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, security_settings]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_security_settings.CreateSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_settings is not None: + request.security_settings = security_settings + + # 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_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_security_settings(self, + request: security_settings.GetSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_settings.SecuritySettings: + r"""Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings]. + name (:class:`str`): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = security_settings.GetSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_security_settings(self, + request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, + *, + security_settings: gcdc_security_settings.SecuritySettings = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. + security_settings (:class:`google.cloud.dialogflowcx_v3.types.SecuritySettings`): + Required. [SecuritySettings] object that contains values + for each of the fields to update. + + This corresponds to the ``security_settings`` 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.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_settings, 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 = gcdc_security_settings.UpdateSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_settings is not None: + request.security_settings = security_settings + if update_mask is not None: + 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_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_settings.name", request.security_settings.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_security_settings(self, + request: security_settings.ListSecuritySettingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecuritySettingsAsyncPager: + r"""Returns the list of all security settings in the + specified location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.ListSecuritySettings][]. + parent (:class:`str`): + Required. The location to list all security settings + 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.dialogflowcx_v3.services.security_settings_service.pagers.ListSecuritySettingsAsyncPager: + The response message for + [SecuritySettings.ListSecuritySettings][]. + + 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 = security_settings.ListSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListSecuritySettingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_security_settings(self, + request: security_settings.DeleteSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.DeleteSecuritySettings][]. + name (:class:`str`): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = security_settings.DeleteSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecuritySettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py new file mode 100644 index 00000000..e2583540 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/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 +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.dialogflowcx_v3.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecuritySettingsServiceGrpcTransport +from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport + + +class SecuritySettingsServiceClientMeta(type): + """Metaclass for the SecuritySettingsService 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[SecuritySettingsServiceTransport]] + _transport_registry["grpc"] = SecuritySettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SecuritySettingsServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SecuritySettingsServiceTransport]: + """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 SecuritySettingsServiceClient(metaclass=SecuritySettingsServiceClientMeta): + """Service for managing security settings for Dialogflow.""" + + @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: + SecuritySettingsServiceClient: 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: + SecuritySettingsServiceClient: 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) -> SecuritySettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SecuritySettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def security_settings_path(project: str,location: str,security_settings: str,) -> str: + """Returns a fully-qualified security_settings string.""" + return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + + @staticmethod + def parse_security_settings_path(path: str) -> Dict[str,str]: + """Parses a security_settings path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def 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, SecuritySettingsServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security settings service 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, SecuritySettingsServiceTransport]): 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, SecuritySettingsServiceTransport): + # transport is a SecuritySettingsServiceTransport 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_security_settings(self, + request: gcdc_security_settings.CreateSecuritySettingsRequest = None, + *, + parent: str = None, + security_settings: gcdc_security_settings.SecuritySettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Create security settings in the specified location. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest): + The request object. The request message for + [SecuritySettings.CreateSecuritySettings][]. + parent (str): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): + Required. The security settings to + create. + + This corresponds to the ``security_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, security_settings]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_security_settings.CreateSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_security_settings.CreateSecuritySettingsRequest): + request = gcdc_security_settings.CreateSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_settings is not None: + request.security_settings = security_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_security_settings(self, + request: security_settings.GetSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_settings.SecuritySettings: + r"""Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest): + The request object. The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings]. + name (str): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 security_settings.GetSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.GetSecuritySettingsRequest): + request = security_settings.GetSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_security_settings] + + # Certain fields should be provided 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_security_settings(self, + request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, + *, + security_settings: gcdc_security_settings.SecuritySettings = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest): + The request object. The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. + security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): + Required. [SecuritySettings] object that contains values + for each of the fields to update. + + This corresponds to the ``security_settings`` 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.dialogflowcx_v3.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_settings, 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 gcdc_security_settings.UpdateSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_security_settings.UpdateSecuritySettingsRequest): + request = gcdc_security_settings.UpdateSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_settings is not None: + request.security_settings = security_settings + if update_mask is not None: + 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_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_settings.name", request.security_settings.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_security_settings(self, + request: security_settings.ListSecuritySettingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecuritySettingsPager: + r"""Returns the list of all security settings in the + specified location. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest): + The request object. The request message for + [SecuritySettings.ListSecuritySettings][]. + parent (str): + Required. The location to list all security settings + 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.dialogflowcx_v3.services.security_settings_service.pagers.ListSecuritySettingsPager: + The response message for + [SecuritySettings.ListSecuritySettings][]. + + 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 security_settings.ListSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.ListSecuritySettingsRequest): + request = security_settings.ListSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListSecuritySettingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_security_settings(self, + request: security_settings.DeleteSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Args: + request (google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest): + The request object. The request message for + [SecuritySettings.DeleteSecuritySettings][]. + name (str): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 security_settings.DeleteSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.DeleteSecuritySettingsRequest): + request = security_settings.DeleteSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_security_settings] + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecuritySettingsServiceClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py new file mode 100644 index 00000000..2989d74d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/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.dialogflowcx_v3.types import security_settings + + +class ListSecuritySettingsPager: + """A pager for iterating through ``list_security_settings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``security_settings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecuritySettings`` requests and continue to iterate + through the ``security_settings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` + 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[..., security_settings.ListSecuritySettingsResponse], + request: security_settings.ListSecuritySettingsRequest, + response: security_settings.ListSecuritySettingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse): + 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 = security_settings.ListSecuritySettingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[security_settings.ListSecuritySettingsResponse]: + 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[security_settings.SecuritySettings]: + for page in self.pages: + yield from page.security_settings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSecuritySettingsAsyncPager: + """A pager for iterating through ``list_security_settings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``security_settings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecuritySettings`` requests and continue to iterate + through the ``security_settings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` + 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[security_settings.ListSecuritySettingsResponse]], + request: security_settings.ListSecuritySettingsRequest, + response: security_settings.ListSecuritySettingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse): + 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 = security_settings.ListSecuritySettingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[security_settings.ListSecuritySettingsResponse]: + 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[security_settings.SecuritySettings]: + async def async_generator(): + async for page in self.pages: + for response in page.security_settings: + 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/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py new file mode 100644 index 00000000..116b7680 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/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 SecuritySettingsServiceTransport +from .grpc import SecuritySettingsServiceGrpcTransport +from .grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecuritySettingsServiceTransport]] +_transport_registry['grpc'] = SecuritySettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SecuritySettingsServiceGrpcAsyncIOTransport + +__all__ = ( + 'SecuritySettingsServiceTransport', + 'SecuritySettingsServiceGrpcTransport', + 'SecuritySettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py new file mode 100644 index 00000000..8c6f4bcb --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/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.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class SecuritySettingsServiceTransport(abc.ABC): + """Abstract transport class for SecuritySettingsService.""" + + 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_security_settings: gapic_v1.method.wrap_method( + self.create_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_security_settings: gapic_v1.method.wrap_method( + self.get_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_security_settings: gapic_v1.method.wrap_method( + self.update_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.list_security_settings: gapic_v1.method.wrap_method( + self.list_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.delete_security_settings: gapic_v1.method.wrap_method( + self.delete_security_settings, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def create_security_settings(self) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + Union[ + gcdc_security_settings.SecuritySettings, + Awaitable[gcdc_security_settings.SecuritySettings] + ]]: + raise NotImplementedError() + + @property + def get_security_settings(self) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + Union[ + security_settings.SecuritySettings, + Awaitable[security_settings.SecuritySettings] + ]]: + raise NotImplementedError() + + @property + def update_security_settings(self) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + Union[ + gcdc_security_settings.SecuritySettings, + Awaitable[gcdc_security_settings.SecuritySettings] + ]]: + raise NotImplementedError() + + @property + def list_security_settings(self) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + Union[ + security_settings.ListSecuritySettingsResponse, + Awaitable[security_settings.ListSecuritySettingsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_security_settings(self) -> Callable[ + [security_settings.DeleteSecuritySettingsRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SecuritySettingsServiceTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py new file mode 100644 index 00000000..5c2f0f6a --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py @@ -0,0 +1,359 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.protobuf import empty_pb2 # type: ignore +from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO + + +class SecuritySettingsServiceGrpcTransport(SecuritySettingsServiceTransport): + """gRPC backend transport for SecuritySettingsService. + + Service for managing security settings for Dialogflow. + + 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_security_settings(self) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + gcdc_security_settings.SecuritySettings]: + r"""Return a callable for the create security settings method over gRPC. + + Create security settings in the specified location. + + Returns: + Callable[[~.CreateSecuritySettingsRequest], + ~.SecuritySettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_settings' not in self._stubs: + self._stubs['create_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/CreateSecuritySettings', + request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['create_security_settings'] + + @property + def get_security_settings(self) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + security_settings.SecuritySettings]: + r"""Return a callable for the get security settings method over gRPC. + + Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Returns: + Callable[[~.GetSecuritySettingsRequest], + ~.SecuritySettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_security_settings' not in self._stubs: + self._stubs['get_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/GetSecuritySettings', + request_serializer=security_settings.GetSecuritySettingsRequest.serialize, + response_deserializer=security_settings.SecuritySettings.deserialize, + ) + return self._stubs['get_security_settings'] + + @property + def update_security_settings(self) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + gcdc_security_settings.SecuritySettings]: + r"""Return a callable for the update security settings method over gRPC. + + Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Returns: + Callable[[~.UpdateSecuritySettingsRequest], + ~.SecuritySettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_settings' not in self._stubs: + self._stubs['update_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/UpdateSecuritySettings', + request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['update_security_settings'] + + @property + def list_security_settings(self) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + security_settings.ListSecuritySettingsResponse]: + r"""Return a callable for the list security settings method over gRPC. + + Returns the list of all security settings in the + specified location. + + Returns: + Callable[[~.ListSecuritySettingsRequest], + ~.ListSecuritySettingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_security_settings' not in self._stubs: + self._stubs['list_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/ListSecuritySettings', + request_serializer=security_settings.ListSecuritySettingsRequest.serialize, + response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, + ) + return self._stubs['list_security_settings'] + + @property + def delete_security_settings(self) -> Callable[ + [security_settings.DeleteSecuritySettingsRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete security settings method over gRPC. + + Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Returns: + Callable[[~.DeleteSecuritySettingsRequest], + ~.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_security_settings' not in self._stubs: + self._stubs['delete_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/DeleteSecuritySettings', + request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_security_settings'] + + +__all__ = ( + 'SecuritySettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..bff5f4d6 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,363 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import 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.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.protobuf import empty_pb2 # type: ignore +from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SecuritySettingsServiceGrpcTransport + + +class SecuritySettingsServiceGrpcAsyncIOTransport(SecuritySettingsServiceTransport): + """gRPC AsyncIO backend transport for SecuritySettingsService. + + Service for managing security settings for Dialogflow. + + 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_security_settings(self) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + Awaitable[gcdc_security_settings.SecuritySettings]]: + r"""Return a callable for the create security settings method over gRPC. + + Create security settings in the specified location. + + Returns: + Callable[[~.CreateSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_settings' not in self._stubs: + self._stubs['create_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/CreateSecuritySettings', + request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['create_security_settings'] + + @property + def get_security_settings(self) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + Awaitable[security_settings.SecuritySettings]]: + r"""Return a callable for the get security settings method over gRPC. + + Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Returns: + Callable[[~.GetSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_security_settings' not in self._stubs: + self._stubs['get_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/GetSecuritySettings', + request_serializer=security_settings.GetSecuritySettingsRequest.serialize, + response_deserializer=security_settings.SecuritySettings.deserialize, + ) + return self._stubs['get_security_settings'] + + @property + def update_security_settings(self) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + Awaitable[gcdc_security_settings.SecuritySettings]]: + r"""Return a callable for the update security settings method over gRPC. + + Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Returns: + Callable[[~.UpdateSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_settings' not in self._stubs: + self._stubs['update_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/UpdateSecuritySettings', + request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['update_security_settings'] + + @property + def list_security_settings(self) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + Awaitable[security_settings.ListSecuritySettingsResponse]]: + r"""Return a callable for the list security settings method over gRPC. + + Returns the list of all security settings in the + specified location. + + Returns: + Callable[[~.ListSecuritySettingsRequest], + Awaitable[~.ListSecuritySettingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_security_settings' not in self._stubs: + self._stubs['list_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/ListSecuritySettings', + request_serializer=security_settings.ListSecuritySettingsRequest.serialize, + response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, + ) + return self._stubs['list_security_settings'] + + @property + def delete_security_settings(self) -> Callable[ + [security_settings.DeleteSecuritySettingsRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete security settings method over gRPC. + + Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. + + Returns: + Callable[[~.DeleteSecuritySettingsRequest], + 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_security_settings' not in self._stubs: + self._stubs['delete_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/DeleteSecuritySettings', + request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_security_settings'] + + +__all__ = ( + 'SecuritySettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py new file mode 100644 index 00000000..fb6678b1 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py new file mode 100644 index 00000000..d58bcc80 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py @@ -0,0 +1,632 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.session_entity_types import pagers +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_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.cx.v3.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. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest`): + The request object. The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. + parent (:class:`str`): + Required. The session to list all session entity types + from. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager: + The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.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. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType]. + name (:class:`str`): + Required. The name of the session entity type. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not 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: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, + *, + parent: str = None, + session_entity_type: gcdc_session_entity_type.SessionEntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Creates a session entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType]. + parent (:class:`str`): + Required. The session to create a session entity type + for. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + 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.dialogflowcx_v3.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.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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, 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 = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session_entity_type is not None: + 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: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, + *, + session_entity_type: gcdc_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]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Updates the specified session entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType]. + session_entity_type (:class:`google.cloud.dialogflowcx_v3.types.SessionEntityType`): + Required. The session entity type to update. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + 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`): + 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.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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([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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session_entity_type is not None: + request.session_entity_type = session_entity_type + if update_mask is not None: + 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. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType]. + name (:class:`str`): + Required. The name of the session entity type to delete. + Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionEntityTypesAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py new file mode 100644 index 00000000..8d15234d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py @@ -0,0 +1,819 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.session_entity_types import pagers +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_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.cx.v3.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,location: str,agent: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, 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.+?)/locations/(?P.+?)/agents/(?P.+?)/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. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest): + The request object. The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. + parent (str): + Required. The session to list all session entity types + from. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.session_entity_types.pagers.ListSessionEntityTypesPager: + The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.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. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest): + The request object. The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType]. + name (str): + Required. The name of the session entity type. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, + *, + parent: str = None, + session_entity_type: gcdc_session_entity_type.SessionEntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Creates a session entity type. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest): + The request object. The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType]. + parent (str): + Required. The session to create a session entity type + for. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + session_entity_type (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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, 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 gcdc_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, gcdc_session_entity_type.CreateSessionEntityTypeRequest): + request = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session_entity_type is not None: + 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: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, + *, + session_entity_type: gcdc_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]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Updates the specified session entity type. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest): + The request object. The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType]. + session_entity_type (google.cloud.dialogflowcx_v3.types.SessionEntityType): + Required. The session entity type to update. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + 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): + 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.dialogflowcx_v3.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at + the user session level (we refer to the entity types + defined at the agent level as "custom entity types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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([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 gcdc_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, gcdc_session_entity_type.UpdateSessionEntityTypeRequest): + request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session_entity_type is not None: + request.session_entity_type = session_entity_type + if update_mask is not None: + 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. + + Args: + request (google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest): + The request object. The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType]. + name (str): + Required. The name of the session entity type to delete. + Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionEntityTypesClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py new file mode 100644 index 00000000..89fb79e7 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListSessionEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListSessionEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.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/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py new file mode 100644 index 00000000..fee52672 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py new file mode 100644 index 00000000..4c384e5b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +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[ + [gcdc_session_entity_type.CreateSessionEntityTypeRequest], + Union[ + gcdc_session_entity_type.SessionEntityType, + Awaitable[gcdc_session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def update_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], + Union[ + gcdc_session_entity_type.SessionEntityType, + Awaitable[gcdc_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/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py new file mode 100644 index 00000000..10d2c22f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/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.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO + + +class SessionEntityTypesGrpcTransport(SessionEntityTypesTransport): + """gRPC backend transport for SessionEntityTypes. + + Service for managing + [SessionEntityTypes][google.cloud.dialogflow.cx.v3.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. + + 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.cx.v3.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. + + 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.cx.v3.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[ + [gcdc_session_entity_type.CreateSessionEntityTypeRequest], + gcdc_session_entity_type.SessionEntityType]: + r"""Return a callable for the create session entity type method over gRPC. + + Creates a session entity type. + + 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.cx.v3.SessionEntityTypes/CreateSessionEntityType', + request_serializer=gcdc_session_entity_type.CreateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['create_session_entity_type'] + + @property + def update_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], + gcdc_session_entity_type.SessionEntityType]: + r"""Return a callable for the update session entity type method over gRPC. + + Updates the specified session entity type. + + 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.cx.v3.SessionEntityTypes/UpdateSessionEntityType', + request_serializer=gcdc_session_entity_type.UpdateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_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. + + 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.cx.v3.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/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py new file mode 100644 index 00000000..e70c7923 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/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.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import empty_pb2 # 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.cx.v3.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. + + 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.cx.v3.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. + + 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.cx.v3.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[ + [gcdc_session_entity_type.CreateSessionEntityTypeRequest], + Awaitable[gcdc_session_entity_type.SessionEntityType]]: + r"""Return a callable for the create session entity type method over gRPC. + + Creates a session entity type. + + 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.cx.v3.SessionEntityTypes/CreateSessionEntityType', + request_serializer=gcdc_session_entity_type.CreateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['create_session_entity_type'] + + @property + def update_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], + Awaitable[gcdc_session_entity_type.SessionEntityType]]: + r"""Return a callable for the update session entity type method over gRPC. + + Updates the specified session entity type. + + 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.cx.v3.SessionEntityTypes/UpdateSessionEntityType', + request_serializer=gcdc_session_entity_type.UpdateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_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. + + 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.cx.v3.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/v3/google/cloud/dialogflowcx_v3/services/sessions/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/__init__.py new file mode 100644 index 00000000..92490cc5 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py new file mode 100644 index 00000000..bde43b86 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py @@ -0,0 +1,460 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.types import audio_config +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import session +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport +from .client import SessionsClient + + +class SessionsAsyncClient: + """A session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] + method to determine user intent and respond. + """ + + _client: SessionsClient + + DEFAULT_ENDPOINT = SessionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SessionsClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(SessionsClient.entity_type_path) + parse_entity_type_path = staticmethod(SessionsClient.parse_entity_type_path) + flow_path = staticmethod(SessionsClient.flow_path) + parse_flow_path = staticmethod(SessionsClient.parse_flow_path) + intent_path = staticmethod(SessionsClient.intent_path) + parse_intent_path = staticmethod(SessionsClient.parse_intent_path) + page_path = staticmethod(SessionsClient.page_path) + parse_page_path = staticmethod(SessionsClient.parse_page_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) + transition_route_group_path = staticmethod(SessionsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(SessionsClient.parse_transition_route_group_path) + webhook_path = staticmethod(SessionsClient.webhook_path) + parse_webhook_path = staticmethod(SessionsClient.parse_webhook_path) + common_billing_account_path = staticmethod(SessionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SessionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SessionsClient.common_folder_path) + parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) + common_organization_path = staticmethod(SessionsClient.common_organization_path) + parse_common_organization_path = staticmethod(SessionsClient.parse_common_organization_path) + common_project_path = staticmethod(SessionsClient.common_project_path) + parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) + common_location_path = staticmethod(SessionsClient.common_location_path) + parse_common_location_path = staticmethod(SessionsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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: session.DetectIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> 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 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.dialogflowcx_v3.types.DetectIntentRequest`): + The request object. The request to detect user's intent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.DetectIntentResponse: + The message returned from the + DetectIntent method. + + """ + # Create or coerce a protobuf request object. + request = session.DetectIntentRequest(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.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.dialogflowcx_v3.types.StreamingDetectIntentRequest`]): + The request object AsyncIterator. The top-level message sent by the + client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] + method. + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.output_audio_config]. + 2. If + [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio.config][google.cloud.dialogflow.cx.v3.AudioInput.config], + all subsequent messages must contain + [query_input.audio.audio][google.cloud.dialogflow.cx.v3.AudioInput.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.cx.v3.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.dialogflowcx_v3.types.StreamingDetectIntentResponse]: + The top-level message returned from the + StreamingDetectIntent method. + + Multiple response messages can be returned in order: + + 1. If the input was set to streaming audio, the first + one or more messages contain recognition_result. + Each recognition_result represents a more complete + transcript of what the user said. The last + recognition_result has is_final set to true. + 2. If enable_partial_response is true, the following + N messages (currently 1 <= N <= 4) contain + detect_intent_response. The first (N-1) + detect_intent_responses will have response_type + set to PARTIAL. The last detect_intent_response + has response_type set to FINAL. If response_type + is false, response stream only contains the final + detect_intent_response. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.streaming_detect_intent, + default_timeout=220.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def match_intent(self, + request: session.MatchIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.MatchIntentResponse: + r"""Returns preliminary intent match results, doesn't + change the session status. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.MatchIntentRequest`): + The request object. Request of [MatchIntent][]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.MatchIntentResponse: + Response of [MatchIntent][]. + """ + # Create or coerce a protobuf request object. + request = session.MatchIntentRequest(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.match_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(( + ("session", request.session), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def fulfill_intent(self, + request: session.FulfillIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.FulfillIntentResponse: + r"""Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.FulfillIntentRequest`): + The request object. Request of [FulfillIntent][] + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FulfillIntentResponse: + Response of [FulfillIntent][] + """ + # Create or coerce a protobuf request object. + request = session.FulfillIntentRequest(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.fulfill_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(( + ("match_intent_request.session", request.match_intent_request.session), + )), + ) + + # 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/client.py new file mode 100644 index 00000000..9ac9dce3 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/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 +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.dialogflowcx_v3.types import audio_config +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import session +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SessionsGrpcTransport +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport + + +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 session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] + method to determine user intent and respond. + """ + + @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 entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_path(project: str,location: str,agent: str,session: str,) -> str: + """Returns a fully-qualified session string.""" + return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format(project=project, location=location, agent=agent, session=session, ) + + @staticmethod + def parse_session_path(path: str) -> Dict[str,str]: + """Parses a session path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_entity_type_path(project: str,location: str,agent: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, 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.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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: session.DetectIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> 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 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.dialogflowcx_v3.types.DetectIntentRequest): + The request object. The request to detect user's intent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.DetectIntentResponse: + The message returned from the + DetectIntent method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a session.DetectIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session.DetectIntentRequest): + request = session.DetectIntentRequest(request) + + # 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.dialogflowcx_v3.types.StreamingDetectIntentRequest]): + The request object iterator. The top-level message sent by the + client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] + method. + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.output_audio_config]. + 2. If + [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio.config][google.cloud.dialogflow.cx.v3.AudioInput.config], + all subsequent messages must contain + [query_input.audio.audio][google.cloud.dialogflow.cx.v3.AudioInput.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.cx.v3.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.dialogflowcx_v3.types.StreamingDetectIntentResponse]: + The top-level message returned from the + StreamingDetectIntent method. + + Multiple response messages can be returned in order: + + 1. If the input was set to streaming audio, the first + one or more messages contain recognition_result. + Each recognition_result represents a more complete + transcript of what the user said. The last + recognition_result has is_final set to true. + 2. If enable_partial_response is true, the following + N messages (currently 1 <= N <= 4) contain + detect_intent_response. The first (N-1) + detect_intent_responses will have response_type + set to PARTIAL. The last detect_intent_response + has response_type set to FINAL. If response_type + is false, response stream only contains the final + detect_intent_response. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.streaming_detect_intent] + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def match_intent(self, + request: session.MatchIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.MatchIntentResponse: + r"""Returns preliminary intent match results, doesn't + change the session status. + + Args: + request (google.cloud.dialogflowcx_v3.types.MatchIntentRequest): + The request object. Request of [MatchIntent][]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.MatchIntentResponse: + Response of [MatchIntent][]. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a session.MatchIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session.MatchIntentRequest): + request = session.MatchIntentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.match_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 fulfill_intent(self, + request: session.FulfillIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.FulfillIntentResponse: + r"""Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Args: + request (google.cloud.dialogflowcx_v3.types.FulfillIntentRequest): + The request object. Request of [FulfillIntent][] + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.FulfillIntentResponse: + Response of [FulfillIntent][] + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a session.FulfillIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session.FulfillIntentRequest): + request = session.FulfillIntentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fulfill_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("match_intent_request.session", request.match_intent_request.session), + )), + ) + + # 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py new file mode 100644 index 00000000..fde19f61 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py new file mode 100644 index 00000000..f5765860 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import session + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +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, + ), + self.match_intent: gapic_v1.method.wrap_method( + self.match_intent, + default_timeout=None, + client_info=client_info, + ), + self.fulfill_intent: gapic_v1.method.wrap_method( + self.fulfill_intent, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def detect_intent(self) -> Callable[ + [session.DetectIntentRequest], + Union[ + session.DetectIntentResponse, + Awaitable[session.DetectIntentResponse] + ]]: + raise NotImplementedError() + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + Union[ + session.StreamingDetectIntentResponse, + Awaitable[session.StreamingDetectIntentResponse] + ]]: + raise NotImplementedError() + + @property + def match_intent(self) -> Callable[ + [session.MatchIntentRequest], + Union[ + session.MatchIntentResponse, + Awaitable[session.MatchIntentResponse] + ]]: + raise NotImplementedError() + + @property + def fulfill_intent(self) -> Callable[ + [session.FulfillIntentRequest], + Union[ + session.FulfillIntentResponse, + Awaitable[session.FulfillIntentResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SessionsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py new file mode 100644 index 00000000..39238871 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.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 warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3.types import session +from .base import SessionsTransport, DEFAULT_CLIENT_INFO + + +class SessionsGrpcTransport(SessionsTransport): + """gRPC backend transport for Sessions. + + A session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] + method to determine user intent and respond. + + 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[ + [session.DetectIntentRequest], + 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 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.cx.v3.Sessions/DetectIntent', + request_serializer=session.DetectIntentRequest.serialize, + response_deserializer=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.cx.v3.Sessions/StreamingDetectIntent', + request_serializer=session.StreamingDetectIntentRequest.serialize, + response_deserializer=session.StreamingDetectIntentResponse.deserialize, + ) + return self._stubs['streaming_detect_intent'] + + @property + def match_intent(self) -> Callable[ + [session.MatchIntentRequest], + session.MatchIntentResponse]: + r"""Return a callable for the match intent method over gRPC. + + Returns preliminary intent match results, doesn't + change the session status. + + Returns: + Callable[[~.MatchIntentRequest], + ~.MatchIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'match_intent' not in self._stubs: + self._stubs['match_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Sessions/MatchIntent', + request_serializer=session.MatchIntentRequest.serialize, + response_deserializer=session.MatchIntentResponse.deserialize, + ) + return self._stubs['match_intent'] + + @property + def fulfill_intent(self) -> Callable[ + [session.FulfillIntentRequest], + session.FulfillIntentResponse]: + r"""Return a callable for the fulfill intent method over gRPC. + + Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Returns: + Callable[[~.FulfillIntentRequest], + ~.FulfillIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fulfill_intent' not in self._stubs: + self._stubs['fulfill_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Sessions/FulfillIntent', + request_serializer=session.FulfillIntentRequest.serialize, + response_deserializer=session.FulfillIntentResponse.deserialize, + ) + return self._stubs['fulfill_intent'] + + +__all__ = ( + 'SessionsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py new file mode 100644 index 00000000..7341f960 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py @@ -0,0 +1,354 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import session +from .base import SessionsTransport, DEFAULT_CLIENT_INFO +from .grpc import SessionsGrpcTransport + + +class SessionsGrpcAsyncIOTransport(SessionsTransport): + """gRPC AsyncIO backend transport for Sessions. + + A session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] + method to determine user intent and respond. + + 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[ + [session.DetectIntentRequest], + Awaitable[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 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.cx.v3.Sessions/DetectIntent', + request_serializer=session.DetectIntentRequest.serialize, + response_deserializer=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.cx.v3.Sessions/StreamingDetectIntent', + request_serializer=session.StreamingDetectIntentRequest.serialize, + response_deserializer=session.StreamingDetectIntentResponse.deserialize, + ) + return self._stubs['streaming_detect_intent'] + + @property + def match_intent(self) -> Callable[ + [session.MatchIntentRequest], + Awaitable[session.MatchIntentResponse]]: + r"""Return a callable for the match intent method over gRPC. + + Returns preliminary intent match results, doesn't + change the session status. + + Returns: + Callable[[~.MatchIntentRequest], + Awaitable[~.MatchIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'match_intent' not in self._stubs: + self._stubs['match_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Sessions/MatchIntent', + request_serializer=session.MatchIntentRequest.serialize, + response_deserializer=session.MatchIntentResponse.deserialize, + ) + return self._stubs['match_intent'] + + @property + def fulfill_intent(self) -> Callable[ + [session.FulfillIntentRequest], + Awaitable[session.FulfillIntentResponse]]: + r"""Return a callable for the fulfill intent method over gRPC. + + Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Returns: + Callable[[~.FulfillIntentRequest], + Awaitable[~.FulfillIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fulfill_intent' not in self._stubs: + self._stubs['fulfill_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Sessions/FulfillIntent', + request_serializer=session.FulfillIntentRequest.serialize, + response_deserializer=session.FulfillIntentResponse.deserialize, + ) + return self._stubs['fulfill_intent'] + + +__all__ = ( + 'SessionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py new file mode 100644 index 00000000..938c210f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__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 TestCasesClient +from .async_client import TestCasesAsyncClient + +__all__ = ( + 'TestCasesClient', + 'TestCasesAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py new file mode 100644 index 00000000..77cf5892 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py @@ -0,0 +1,1073 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.test_cases import pagers +from google.cloud.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport +from .client import TestCasesClient + + +class TestCasesAsyncClient: + """Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. + """ + + _client: TestCasesClient + + DEFAULT_ENDPOINT = TestCasesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TestCasesClient.DEFAULT_MTLS_ENDPOINT + + agent_path = staticmethod(TestCasesClient.agent_path) + parse_agent_path = staticmethod(TestCasesClient.parse_agent_path) + entity_type_path = staticmethod(TestCasesClient.entity_type_path) + parse_entity_type_path = staticmethod(TestCasesClient.parse_entity_type_path) + environment_path = staticmethod(TestCasesClient.environment_path) + parse_environment_path = staticmethod(TestCasesClient.parse_environment_path) + flow_path = staticmethod(TestCasesClient.flow_path) + parse_flow_path = staticmethod(TestCasesClient.parse_flow_path) + intent_path = staticmethod(TestCasesClient.intent_path) + parse_intent_path = staticmethod(TestCasesClient.parse_intent_path) + page_path = staticmethod(TestCasesClient.page_path) + parse_page_path = staticmethod(TestCasesClient.parse_page_path) + test_case_path = staticmethod(TestCasesClient.test_case_path) + parse_test_case_path = staticmethod(TestCasesClient.parse_test_case_path) + test_case_result_path = staticmethod(TestCasesClient.test_case_result_path) + parse_test_case_result_path = staticmethod(TestCasesClient.parse_test_case_result_path) + transition_route_group_path = staticmethod(TestCasesClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(TestCasesClient.parse_transition_route_group_path) + webhook_path = staticmethod(TestCasesClient.webhook_path) + parse_webhook_path = staticmethod(TestCasesClient.parse_webhook_path) + common_billing_account_path = staticmethod(TestCasesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TestCasesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TestCasesClient.common_folder_path) + parse_common_folder_path = staticmethod(TestCasesClient.parse_common_folder_path) + common_organization_path = staticmethod(TestCasesClient.common_organization_path) + parse_common_organization_path = staticmethod(TestCasesClient.parse_common_organization_path) + common_project_path = staticmethod(TestCasesClient.common_project_path) + parse_common_project_path = staticmethod(TestCasesClient.parse_common_project_path) + common_location_path = staticmethod(TestCasesClient.common_location_path) + parse_common_location_path = staticmethod(TestCasesClient.parse_common_location_path) + + @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: + TestCasesAsyncClient: The constructed client. + """ + return TestCasesClient.from_service_account_info.__func__(TestCasesAsyncClient, 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: + TestCasesAsyncClient: The constructed client. + """ + return TestCasesClient.from_service_account_file.__func__(TestCasesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> TestCasesTransport: + """Returns the transport used by the client instance. + + Returns: + TestCasesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(TestCasesClient).get_transport_class, type(TestCasesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, TestCasesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the test cases 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, ~.TestCasesTransport]): 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 = TestCasesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_test_cases(self, + request: test_case.ListTestCasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCasesAsyncPager: + r"""Fetches a list of test cases for a given agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListTestCasesRequest`): + The request object. The request message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. + parent (:class:`str`): + Required. The agent to list all pages for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCasesAsyncPager: + The response message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. + + 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 = test_case.ListTestCasesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListTestCasesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_delete_test_cases(self, + request: test_case.BatchDeleteTestCasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Batch deletes test cases. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest`): + The request object. The request message for + [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases]. + parent (:class:`str`): + Required. The agent to delete test cases from. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = test_case.BatchDeleteTestCasesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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 get_test_case(self, + request: test_case.GetTestCaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCase: + r"""Gets a test case. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetTestCaseRequest`): + The request object. The request message for + [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3.TestCases.GetTestCase]. + name (:class:`str`): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = test_case.GetTestCaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_test_case(self, + request: gcdc_test_case.CreateTestCaseRequest = None, + *, + parent: str = None, + test_case: gcdc_test_case.TestCase = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Creates a test case for the given agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest`): + The request object. The request message for + [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase]. + parent (:class:`str`): + Required. The agent to create the test case for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_case (:class:`google.cloud.dialogflowcx_v3.types.TestCase`): + Required. The test case to create. + This corresponds to the ``test_case`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, test_case]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_test_case.CreateTestCaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if test_case is not None: + request.test_case = test_case + + # 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_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_test_case(self, + request: gcdc_test_case.UpdateTestCaseRequest = None, + *, + test_case: gcdc_test_case.TestCase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Updates the specified test case. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest`): + The request object. The request message for + [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase]. + test_case (:class:`google.cloud.dialogflowcx_v3.types.TestCase`): + Required. The test case to update. + This corresponds to the ``test_case`` 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 should be + updated. The + [``creationTime``][google.cloud.dialogflow.cx.v3.TestCase.creation_time] + and + [``lastTestResult``][google.cloud.dialogflow.cx.v3.TestCase.last_test_result] + cannot 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.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([test_case, 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 = gcdc_test_case.UpdateTestCaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if test_case is not None: + request.test_case = test_case + if update_mask is not None: + 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_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("test_case.name", request.test_case.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_test_case(self, + request: test_case.RunTestCaseRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off a test case run. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.RunTestCaseRequest`): + The request object. The request message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.RunTestCaseResponse` + The response message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. + + """ + # Create or coerce a protobuf request object. + request = test_case.RunTestCaseRequest(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.run_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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, + test_case.RunTestCaseResponse, + metadata_type=test_case.RunTestCaseMetadata, + ) + + # Done; return the response. + return response + + async def batch_run_test_cases(self, + request: test_case.BatchRunTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off a batch run of test cases. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest`): + The request object. The request message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesResponse` + The response message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. + + """ + # Create or coerce a protobuf request object. + request = test_case.BatchRunTestCasesRequest(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_run_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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, + test_case.BatchRunTestCasesResponse, + metadata_type=test_case.BatchRunTestCasesMetadata, + ) + + # Done; return the response. + return response + + async def calculate_coverage(self, + request: test_case.CalculateCoverageRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.CalculateCoverageResponse: + r"""Calculates the test coverage for an agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest`): + The request object. The request message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.CalculateCoverageResponse: + The response message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + + """ + # Create or coerce a protobuf request object. + request = test_case.CalculateCoverageRequest(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.calculate_coverage, + default_timeout=None, + client_info=DEFAULT_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", request.agent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_test_cases(self, + request: test_case.ImportTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the test cases from a Cloud Storage bucket or + a local file. It always creates new test cases and won't + overwite any existing ones. The provided ID in the + imported test case is neglected. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest`): + The request object. The request message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesResponse` + The response message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + + """ + # Create or coerce a protobuf request object. + request = test_case.ImportTestCasesRequest(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_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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, + test_case.ImportTestCasesResponse, + metadata_type=test_case.ImportTestCasesMetadata, + ) + + # Done; return the response. + return response + + async def export_test_cases(self, + request: test_case.ExportTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the test cases under the agent to a Cloud + Storage bucket or a local file. Filter can be applied to + export a subset of test cases. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest`): + The request object. The request message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesResponse` + The response message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + + """ + # Create or coerce a protobuf request object. + request = test_case.ExportTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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, + test_case.ExportTestCasesResponse, + metadata_type=test_case.ExportTestCasesMetadata, + ) + + # Done; return the response. + return response + + async def list_test_case_results(self, + request: test_case.ListTestCaseResultsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCaseResultsAsyncPager: + r"""Fetches a list of results for a given test case. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest`): + The request object. The request message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. + parent (:class:`str`): + Required. The test case to list results for. Format: + ``projects//locations//agents// testCases/``. + Specify a ``-`` as a wildcard for TestCase ID to list + results across multiple test cases. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCaseResultsAsyncPager: + The response message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. + + 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 = test_case.ListTestCaseResultsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_test_case_results, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListTestCaseResultsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_test_case_result(self, + request: test_case.GetTestCaseResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCaseResult: + r"""Gets a test case result. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest`): + The request object. The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. + name (:class:`str`): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCaseResult: + Represents a result from running a + test case in an agent environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = test_case.GetTestCaseResultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_test_case_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TestCasesAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py new file mode 100644 index 00000000..4f2ae94d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py @@ -0,0 +1,1346 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.test_cases import pagers +from google.cloud.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TestCasesGrpcTransport +from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport + + +class TestCasesClientMeta(type): + """Metaclass for the TestCases 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[TestCasesTransport]] + _transport_registry["grpc"] = TestCasesGrpcTransport + _transport_registry["grpc_asyncio"] = TestCasesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[TestCasesTransport]: + """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 TestCasesClient(metaclass=TestCasesClientMeta): + """Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. + """ + + @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: + TestCasesClient: 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: + TestCasesClient: 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) -> TestCasesTransport: + """Returns the transport used by the client instance. + + Returns: + TestCasesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path(project: str,location: str,agent: str,) -> str: + """Returns a fully-qualified agent string.""" + return "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str,str]: + """Parses a agent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def environment_path(project: str,location: str,agent: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def test_case_path(project: str,location: str,agent: str,test_case: str,) -> str: + """Returns a fully-qualified test_case string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(project=project, location=location, agent=agent, test_case=test_case, ) + + @staticmethod + def parse_test_case_path(path: str) -> Dict[str,str]: + """Parses a test_case path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def test_case_result_path(project: str,location: str,agent: str,test_case: str,result: str,) -> str: + """Returns a fully-qualified test_case_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) + + @staticmethod + def parse_test_case_result_path(path: str) -> Dict[str,str]: + """Parses a test_case_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, TestCasesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the test cases 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, TestCasesTransport]): 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, TestCasesTransport): + # transport is a TestCasesTransport 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_test_cases(self, + request: test_case.ListTestCasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCasesPager: + r"""Fetches a list of test cases for a given agent. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListTestCasesRequest): + The request object. The request message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. + parent (str): + Required. The agent to list all pages for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCasesPager: + The response message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. + + 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 test_case.ListTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ListTestCasesRequest): + request = test_case.ListTestCasesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListTestCasesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_delete_test_cases(self, + request: test_case.BatchDeleteTestCasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Batch deletes test cases. + + Args: + request (google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest): + The request object. The request message for + [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases]. + parent (str): + Required. The agent to delete test cases from. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 test_case.BatchDeleteTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.BatchDeleteTestCasesRequest): + request = test_case.BatchDeleteTestCasesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_test_cases] + + # Certain fields should be 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 get_test_case(self, + request: test_case.GetTestCaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCase: + r"""Gets a test case. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetTestCaseRequest): + The request object. The request message for + [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3.TestCases.GetTestCase]. + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a test_case.GetTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.GetTestCaseRequest): + request = test_case.GetTestCaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_test_case] + + # Certain fields should be provided 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_test_case(self, + request: gcdc_test_case.CreateTestCaseRequest = None, + *, + parent: str = None, + test_case: gcdc_test_case.TestCase = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Creates a test case for the given agent. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest): + The request object. The request message for + [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase]. + parent (str): + Required. The agent to create the test case for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_case (google.cloud.dialogflowcx_v3.types.TestCase): + Required. The test case to create. + This corresponds to the ``test_case`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, test_case]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_test_case.CreateTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_test_case.CreateTestCaseRequest): + request = gcdc_test_case.CreateTestCaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if test_case is not None: + request.test_case = test_case + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_test_case] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_test_case(self, + request: gcdc_test_case.UpdateTestCaseRequest = None, + *, + test_case: gcdc_test_case.TestCase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Updates the specified test case. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest): + The request object. The request message for + [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase]. + test_case (google.cloud.dialogflowcx_v3.types.TestCase): + Required. The test case to update. + This corresponds to the ``test_case`` 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 should be + updated. The + [``creationTime``][google.cloud.dialogflow.cx.v3.TestCase.creation_time] + and + [``lastTestResult``][google.cloud.dialogflow.cx.v3.TestCase.last_test_result] + cannot 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.dialogflowcx_v3.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([test_case, 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 gcdc_test_case.UpdateTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_test_case.UpdateTestCaseRequest): + request = gcdc_test_case.UpdateTestCaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if test_case is not None: + request.test_case = test_case + if update_mask is not None: + 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_test_case] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("test_case.name", request.test_case.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_test_case(self, + request: test_case.RunTestCaseRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Kicks off a test case run. + + Args: + request (google.cloud.dialogflowcx_v3.types.RunTestCaseRequest): + The request object. The request message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.RunTestCaseResponse` + The response message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.RunTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.RunTestCaseRequest): + request = test_case.RunTestCaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_test_case] + + # Certain fields should be provided 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, + test_case.RunTestCaseResponse, + metadata_type=test_case.RunTestCaseMetadata, + ) + + # Done; return the response. + return response + + def batch_run_test_cases(self, + request: test_case.BatchRunTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Kicks off a batch run of test cases. + + Args: + request (google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest): + The request object. The request message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesResponse` + The response message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.BatchRunTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.BatchRunTestCasesRequest): + request = test_case.BatchRunTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_run_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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, + test_case.BatchRunTestCasesResponse, + metadata_type=test_case.BatchRunTestCasesMetadata, + ) + + # Done; return the response. + return response + + def calculate_coverage(self, + request: test_case.CalculateCoverageRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.CalculateCoverageResponse: + r"""Calculates the test coverage for an agent. + + Args: + request (google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest): + The request object. The request message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.CalculateCoverageResponse: + The response message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.CalculateCoverageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.CalculateCoverageRequest): + request = test_case.CalculateCoverageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.calculate_coverage] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent", request.agent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_test_cases(self, + request: test_case.ImportTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports the test cases from a Cloud Storage bucket or + a local file. It always creates new test cases and won't + overwite any existing ones. The provided ID in the + imported test case is neglected. + + Args: + request (google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest): + The request object. The request message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesResponse` + The response message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.ImportTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ImportTestCasesRequest): + request = test_case.ImportTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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, + test_case.ImportTestCasesResponse, + metadata_type=test_case.ImportTestCasesMetadata, + ) + + # Done; return the response. + return response + + def export_test_cases(self, + request: test_case.ExportTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the test cases under the agent to a Cloud + Storage bucket or a local file. Filter can be applied to + export a subset of test cases. + + Args: + request (google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest): + The request object. The request message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesResponse` + The response message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.ExportTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ExportTestCasesRequest): + request = test_case.ExportTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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, + test_case.ExportTestCasesResponse, + metadata_type=test_case.ExportTestCasesMetadata, + ) + + # Done; return the response. + return response + + def list_test_case_results(self, + request: test_case.ListTestCaseResultsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCaseResultsPager: + r"""Fetches a list of results for a given test case. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest): + The request object. The request message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. + parent (str): + Required. The test case to list results for. Format: + ``projects//locations//agents// testCases/``. + Specify a ``-`` as a wildcard for TestCase ID to list + results across multiple test cases. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCaseResultsPager: + The response message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. + + 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 test_case.ListTestCaseResultsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ListTestCaseResultsRequest): + request = test_case.ListTestCaseResultsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_test_case_results] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListTestCaseResultsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_test_case_result(self, + request: test_case.GetTestCaseResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCaseResult: + r"""Gets a test case result. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest): + The request object. The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TestCaseResult: + Represents a result from running a + test case in an agent environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a test_case.GetTestCaseResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.GetTestCaseResultRequest): + request = test_case.GetTestCaseResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_test_case_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TestCasesClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py new file mode 100644 index 00000000..57840934 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/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.dialogflowcx_v3.types import test_case + + +class ListTestCasesPager: + """A pager for iterating through ``list_test_cases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``test_cases`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTestCases`` requests and continue to iterate + through the ``test_cases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` + 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[..., test_case.ListTestCasesResponse], + request: test_case.ListTestCasesRequest, + response: test_case.ListTestCasesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTestCasesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTestCasesResponse): + 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 = test_case.ListTestCasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[test_case.ListTestCasesResponse]: + 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[test_case.TestCase]: + for page in self.pages: + yield from page.test_cases + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTestCasesAsyncPager: + """A pager for iterating through ``list_test_cases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``test_cases`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTestCases`` requests and continue to iterate + through the ``test_cases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` + 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[test_case.ListTestCasesResponse]], + request: test_case.ListTestCasesRequest, + response: test_case.ListTestCasesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTestCasesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTestCasesResponse): + 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 = test_case.ListTestCasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[test_case.ListTestCasesResponse]: + 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[test_case.TestCase]: + async def async_generator(): + async for page in self.pages: + for response in page.test_cases: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTestCaseResultsPager: + """A pager for iterating through ``list_test_case_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``test_case_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTestCaseResults`` requests and continue to iterate + through the ``test_case_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` + 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[..., test_case.ListTestCaseResultsResponse], + request: test_case.ListTestCaseResultsRequest, + response: test_case.ListTestCaseResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse): + 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 = test_case.ListTestCaseResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[test_case.ListTestCaseResultsResponse]: + 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[test_case.TestCaseResult]: + for page in self.pages: + yield from page.test_case_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTestCaseResultsAsyncPager: + """A pager for iterating through ``list_test_case_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``test_case_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTestCaseResults`` requests and continue to iterate + through the ``test_case_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` + 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[test_case.ListTestCaseResultsResponse]], + request: test_case.ListTestCaseResultsRequest, + response: test_case.ListTestCaseResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse): + 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 = test_case.ListTestCaseResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[test_case.ListTestCaseResultsResponse]: + 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[test_case.TestCaseResult]: + async def async_generator(): + async for page in self.pages: + for response in page.test_case_results: + 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/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py new file mode 100644 index 00000000..52d2730d --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/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 TestCasesTransport +from .grpc import TestCasesGrpcTransport +from .grpc_asyncio import TestCasesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TestCasesTransport]] +_transport_registry['grpc'] = TestCasesGrpcTransport +_transport_registry['grpc_asyncio'] = TestCasesGrpcAsyncIOTransport + +__all__ = ( + 'TestCasesTransport', + 'TestCasesGrpcTransport', + 'TestCasesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py new file mode 100644 index 00000000..642ea724 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py @@ -0,0 +1,346 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 # 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-dialogflowcx', + ).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 TestCasesTransport(abc.ABC): + """Abstract transport class for TestCases.""" + + 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_test_cases: gapic_v1.method.wrap_method( + self.list_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_test_cases: gapic_v1.method.wrap_method( + self.batch_delete_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.get_test_case: gapic_v1.method.wrap_method( + self.get_test_case, + default_timeout=None, + client_info=client_info, + ), + self.create_test_case: gapic_v1.method.wrap_method( + self.create_test_case, + default_timeout=None, + client_info=client_info, + ), + self.update_test_case: gapic_v1.method.wrap_method( + self.update_test_case, + default_timeout=None, + client_info=client_info, + ), + self.run_test_case: gapic_v1.method.wrap_method( + self.run_test_case, + default_timeout=None, + client_info=client_info, + ), + self.batch_run_test_cases: gapic_v1.method.wrap_method( + self.batch_run_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.calculate_coverage: gapic_v1.method.wrap_method( + self.calculate_coverage, + default_timeout=None, + client_info=client_info, + ), + self.import_test_cases: gapic_v1.method.wrap_method( + self.import_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.export_test_cases: gapic_v1.method.wrap_method( + self.export_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.list_test_case_results: gapic_v1.method.wrap_method( + self.list_test_case_results, + default_timeout=None, + client_info=client_info, + ), + self.get_test_case_result: gapic_v1.method.wrap_method( + self.get_test_case_result, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_test_cases(self) -> Callable[ + [test_case.ListTestCasesRequest], + Union[ + test_case.ListTestCasesResponse, + Awaitable[test_case.ListTestCasesResponse] + ]]: + raise NotImplementedError() + + @property + def batch_delete_test_cases(self) -> Callable[ + [test_case.BatchDeleteTestCasesRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_test_case(self) -> Callable[ + [test_case.GetTestCaseRequest], + Union[ + test_case.TestCase, + Awaitable[test_case.TestCase] + ]]: + raise NotImplementedError() + + @property + def create_test_case(self) -> Callable[ + [gcdc_test_case.CreateTestCaseRequest], + Union[ + gcdc_test_case.TestCase, + Awaitable[gcdc_test_case.TestCase] + ]]: + raise NotImplementedError() + + @property + def update_test_case(self) -> Callable[ + [gcdc_test_case.UpdateTestCaseRequest], + Union[ + gcdc_test_case.TestCase, + Awaitable[gcdc_test_case.TestCase] + ]]: + raise NotImplementedError() + + @property + def run_test_case(self) -> Callable[ + [test_case.RunTestCaseRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_run_test_cases(self) -> Callable[ + [test_case.BatchRunTestCasesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def calculate_coverage(self) -> Callable[ + [test_case.CalculateCoverageRequest], + Union[ + test_case.CalculateCoverageResponse, + Awaitable[test_case.CalculateCoverageResponse] + ]]: + raise NotImplementedError() + + @property + def import_test_cases(self) -> Callable[ + [test_case.ImportTestCasesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_test_cases(self) -> Callable[ + [test_case.ExportTestCasesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_test_case_results(self) -> Callable[ + [test_case.ListTestCaseResultsRequest], + Union[ + test_case.ListTestCaseResultsResponse, + Awaitable[test_case.ListTestCaseResultsResponse] + ]]: + raise NotImplementedError() + + @property + def get_test_case_result(self) -> Callable[ + [test_case.GetTestCaseResultRequest], + Union[ + test_case.TestCaseResult, + Awaitable[test_case.TestCaseResult] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'TestCasesTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py new file mode 100644 index 00000000..9b134bfb --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py @@ -0,0 +1,562 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import TestCasesTransport, DEFAULT_CLIENT_INFO + + +class TestCasesGrpcTransport(TestCasesTransport): + """gRPC backend transport for TestCases. + + Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. + + 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_test_cases(self) -> Callable[ + [test_case.ListTestCasesRequest], + test_case.ListTestCasesResponse]: + r"""Return a callable for the list test cases method over gRPC. + + Fetches a list of test cases for a given agent. + + Returns: + Callable[[~.ListTestCasesRequest], + ~.ListTestCasesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_cases' not in self._stubs: + self._stubs['list_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCases', + request_serializer=test_case.ListTestCasesRequest.serialize, + response_deserializer=test_case.ListTestCasesResponse.deserialize, + ) + return self._stubs['list_test_cases'] + + @property + def batch_delete_test_cases(self) -> Callable[ + [test_case.BatchDeleteTestCasesRequest], + empty_pb2.Empty]: + r"""Return a callable for the batch delete test cases method over gRPC. + + Batch deletes test cases. + + Returns: + Callable[[~.BatchDeleteTestCasesRequest], + ~.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 'batch_delete_test_cases' not in self._stubs: + self._stubs['batch_delete_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/BatchDeleteTestCases', + request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['batch_delete_test_cases'] + + @property + def get_test_case(self) -> Callable[ + [test_case.GetTestCaseRequest], + test_case.TestCase]: + r"""Return a callable for the get test case method over gRPC. + + Gets a test case. + + Returns: + Callable[[~.GetTestCaseRequest], + ~.TestCase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case' not in self._stubs: + self._stubs['get_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCase', + request_serializer=test_case.GetTestCaseRequest.serialize, + response_deserializer=test_case.TestCase.deserialize, + ) + return self._stubs['get_test_case'] + + @property + def create_test_case(self) -> Callable[ + [gcdc_test_case.CreateTestCaseRequest], + gcdc_test_case.TestCase]: + r"""Return a callable for the create test case method over gRPC. + + Creates a test case for the given agent. + + Returns: + Callable[[~.CreateTestCaseRequest], + ~.TestCase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_test_case' not in self._stubs: + self._stubs['create_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/CreateTestCase', + request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['create_test_case'] + + @property + def update_test_case(self) -> Callable[ + [gcdc_test_case.UpdateTestCaseRequest], + gcdc_test_case.TestCase]: + r"""Return a callable for the update test case method over gRPC. + + Updates the specified test case. + + Returns: + Callable[[~.UpdateTestCaseRequest], + ~.TestCase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_test_case' not in self._stubs: + self._stubs['update_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/UpdateTestCase', + request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['update_test_case'] + + @property + def run_test_case(self) -> Callable[ + [test_case.RunTestCaseRequest], + operations_pb2.Operation]: + r"""Return a callable for the run test case method over gRPC. + + Kicks off a test case run. + + Returns: + Callable[[~.RunTestCaseRequest], + ~.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 'run_test_case' not in self._stubs: + self._stubs['run_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/RunTestCase', + request_serializer=test_case.RunTestCaseRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_test_case'] + + @property + def batch_run_test_cases(self) -> Callable[ + [test_case.BatchRunTestCasesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch run test cases method over gRPC. + + Kicks off a batch run of test cases. + + Returns: + Callable[[~.BatchRunTestCasesRequest], + ~.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_run_test_cases' not in self._stubs: + self._stubs['batch_run_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/BatchRunTestCases', + request_serializer=test_case.BatchRunTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_run_test_cases'] + + @property + def calculate_coverage(self) -> Callable[ + [test_case.CalculateCoverageRequest], + test_case.CalculateCoverageResponse]: + r"""Return a callable for the calculate coverage method over gRPC. + + Calculates the test coverage for an agent. + + Returns: + Callable[[~.CalculateCoverageRequest], + ~.CalculateCoverageResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'calculate_coverage' not in self._stubs: + self._stubs['calculate_coverage'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/CalculateCoverage', + request_serializer=test_case.CalculateCoverageRequest.serialize, + response_deserializer=test_case.CalculateCoverageResponse.deserialize, + ) + return self._stubs['calculate_coverage'] + + @property + def import_test_cases(self) -> Callable[ + [test_case.ImportTestCasesRequest], + operations_pb2.Operation]: + r"""Return a callable for the import test cases method over gRPC. + + Imports the test cases from a Cloud Storage bucket or + a local file. It always creates new test cases and won't + overwite any existing ones. The provided ID in the + imported test case is neglected. + + Returns: + Callable[[~.ImportTestCasesRequest], + ~.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_test_cases' not in self._stubs: + self._stubs['import_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ImportTestCases', + request_serializer=test_case.ImportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_test_cases'] + + @property + def export_test_cases(self) -> Callable[ + [test_case.ExportTestCasesRequest], + operations_pb2.Operation]: + r"""Return a callable for the export test cases method over gRPC. + + Exports the test cases under the agent to a Cloud + Storage bucket or a local file. Filter can be applied to + export a subset of test cases. + + Returns: + Callable[[~.ExportTestCasesRequest], + ~.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_test_cases' not in self._stubs: + self._stubs['export_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ExportTestCases', + request_serializer=test_case.ExportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_test_cases'] + + @property + def list_test_case_results(self) -> Callable[ + [test_case.ListTestCaseResultsRequest], + test_case.ListTestCaseResultsResponse]: + r"""Return a callable for the list test case results method over gRPC. + + Fetches a list of results for a given test case. + + Returns: + Callable[[~.ListTestCaseResultsRequest], + ~.ListTestCaseResultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_case_results' not in self._stubs: + self._stubs['list_test_case_results'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCaseResults', + request_serializer=test_case.ListTestCaseResultsRequest.serialize, + response_deserializer=test_case.ListTestCaseResultsResponse.deserialize, + ) + return self._stubs['list_test_case_results'] + + @property + def get_test_case_result(self) -> Callable[ + [test_case.GetTestCaseResultRequest], + test_case.TestCaseResult]: + r"""Return a callable for the get test case result method over gRPC. + + Gets a test case result. + + Returns: + Callable[[~.GetTestCaseResultRequest], + ~.TestCaseResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case_result' not in self._stubs: + self._stubs['get_test_case_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCaseResult', + request_serializer=test_case.GetTestCaseResultRequest.serialize, + response_deserializer=test_case.TestCaseResult.deserialize, + ) + return self._stubs['get_test_case_result'] + + +__all__ = ( + 'TestCasesGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py new file mode 100644 index 00000000..35f5085e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py @@ -0,0 +1,566 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import TestCasesTransport, DEFAULT_CLIENT_INFO +from .grpc import TestCasesGrpcTransport + + +class TestCasesGrpcAsyncIOTransport(TestCasesTransport): + """gRPC AsyncIO backend transport for TestCases. + + Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. + + 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_test_cases(self) -> Callable[ + [test_case.ListTestCasesRequest], + Awaitable[test_case.ListTestCasesResponse]]: + r"""Return a callable for the list test cases method over gRPC. + + Fetches a list of test cases for a given agent. + + Returns: + Callable[[~.ListTestCasesRequest], + Awaitable[~.ListTestCasesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_cases' not in self._stubs: + self._stubs['list_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCases', + request_serializer=test_case.ListTestCasesRequest.serialize, + response_deserializer=test_case.ListTestCasesResponse.deserialize, + ) + return self._stubs['list_test_cases'] + + @property + def batch_delete_test_cases(self) -> Callable[ + [test_case.BatchDeleteTestCasesRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the batch delete test cases method over gRPC. + + Batch deletes test cases. + + Returns: + Callable[[~.BatchDeleteTestCasesRequest], + 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 'batch_delete_test_cases' not in self._stubs: + self._stubs['batch_delete_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/BatchDeleteTestCases', + request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['batch_delete_test_cases'] + + @property + def get_test_case(self) -> Callable[ + [test_case.GetTestCaseRequest], + Awaitable[test_case.TestCase]]: + r"""Return a callable for the get test case method over gRPC. + + Gets a test case. + + Returns: + Callable[[~.GetTestCaseRequest], + Awaitable[~.TestCase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case' not in self._stubs: + self._stubs['get_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCase', + request_serializer=test_case.GetTestCaseRequest.serialize, + response_deserializer=test_case.TestCase.deserialize, + ) + return self._stubs['get_test_case'] + + @property + def create_test_case(self) -> Callable[ + [gcdc_test_case.CreateTestCaseRequest], + Awaitable[gcdc_test_case.TestCase]]: + r"""Return a callable for the create test case method over gRPC. + + Creates a test case for the given agent. + + Returns: + Callable[[~.CreateTestCaseRequest], + Awaitable[~.TestCase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_test_case' not in self._stubs: + self._stubs['create_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/CreateTestCase', + request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['create_test_case'] + + @property + def update_test_case(self) -> Callable[ + [gcdc_test_case.UpdateTestCaseRequest], + Awaitable[gcdc_test_case.TestCase]]: + r"""Return a callable for the update test case method over gRPC. + + Updates the specified test case. + + Returns: + Callable[[~.UpdateTestCaseRequest], + Awaitable[~.TestCase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_test_case' not in self._stubs: + self._stubs['update_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/UpdateTestCase', + request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['update_test_case'] + + @property + def run_test_case(self) -> Callable[ + [test_case.RunTestCaseRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run test case method over gRPC. + + Kicks off a test case run. + + Returns: + Callable[[~.RunTestCaseRequest], + 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 'run_test_case' not in self._stubs: + self._stubs['run_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/RunTestCase', + request_serializer=test_case.RunTestCaseRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_test_case'] + + @property + def batch_run_test_cases(self) -> Callable[ + [test_case.BatchRunTestCasesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch run test cases method over gRPC. + + Kicks off a batch run of test cases. + + Returns: + Callable[[~.BatchRunTestCasesRequest], + 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_run_test_cases' not in self._stubs: + self._stubs['batch_run_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/BatchRunTestCases', + request_serializer=test_case.BatchRunTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_run_test_cases'] + + @property + def calculate_coverage(self) -> Callable[ + [test_case.CalculateCoverageRequest], + Awaitable[test_case.CalculateCoverageResponse]]: + r"""Return a callable for the calculate coverage method over gRPC. + + Calculates the test coverage for an agent. + + Returns: + Callable[[~.CalculateCoverageRequest], + Awaitable[~.CalculateCoverageResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'calculate_coverage' not in self._stubs: + self._stubs['calculate_coverage'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/CalculateCoverage', + request_serializer=test_case.CalculateCoverageRequest.serialize, + response_deserializer=test_case.CalculateCoverageResponse.deserialize, + ) + return self._stubs['calculate_coverage'] + + @property + def import_test_cases(self) -> Callable[ + [test_case.ImportTestCasesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import test cases method over gRPC. + + Imports the test cases from a Cloud Storage bucket or + a local file. It always creates new test cases and won't + overwite any existing ones. The provided ID in the + imported test case is neglected. + + Returns: + Callable[[~.ImportTestCasesRequest], + 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_test_cases' not in self._stubs: + self._stubs['import_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ImportTestCases', + request_serializer=test_case.ImportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_test_cases'] + + @property + def export_test_cases(self) -> Callable[ + [test_case.ExportTestCasesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export test cases method over gRPC. + + Exports the test cases under the agent to a Cloud + Storage bucket or a local file. Filter can be applied to + export a subset of test cases. + + Returns: + Callable[[~.ExportTestCasesRequest], + 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_test_cases' not in self._stubs: + self._stubs['export_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ExportTestCases', + request_serializer=test_case.ExportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_test_cases'] + + @property + def list_test_case_results(self) -> Callable[ + [test_case.ListTestCaseResultsRequest], + Awaitable[test_case.ListTestCaseResultsResponse]]: + r"""Return a callable for the list test case results method over gRPC. + + Fetches a list of results for a given test case. + + Returns: + Callable[[~.ListTestCaseResultsRequest], + Awaitable[~.ListTestCaseResultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_case_results' not in self._stubs: + self._stubs['list_test_case_results'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCaseResults', + request_serializer=test_case.ListTestCaseResultsRequest.serialize, + response_deserializer=test_case.ListTestCaseResultsResponse.deserialize, + ) + return self._stubs['list_test_case_results'] + + @property + def get_test_case_result(self) -> Callable[ + [test_case.GetTestCaseResultRequest], + Awaitable[test_case.TestCaseResult]]: + r"""Return a callable for the get test case result method over gRPC. + + Gets a test case result. + + Returns: + Callable[[~.GetTestCaseResultRequest], + Awaitable[~.TestCaseResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case_result' not in self._stubs: + self._stubs['get_test_case_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCaseResult', + request_serializer=test_case.GetTestCaseResultRequest.serialize, + response_deserializer=test_case.TestCaseResult.deserialize, + ) + return self._stubs['get_test_case_result'] + + +__all__ = ( + 'TestCasesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py new file mode 100644 index 00000000..8e43702f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__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 TransitionRouteGroupsClient +from .async_client import TransitionRouteGroupsAsyncClient + +__all__ = ( + 'TransitionRouteGroupsClient', + 'TransitionRouteGroupsAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py new file mode 100644 index 00000000..b71fadf0 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.transition_route_groups import pagers +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport +from .client import TransitionRouteGroupsClient + + +class TransitionRouteGroupsAsyncClient: + """Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + """ + + _client: TransitionRouteGroupsClient + + DEFAULT_ENDPOINT = TransitionRouteGroupsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TransitionRouteGroupsClient.DEFAULT_MTLS_ENDPOINT + + flow_path = staticmethod(TransitionRouteGroupsClient.flow_path) + parse_flow_path = staticmethod(TransitionRouteGroupsClient.parse_flow_path) + intent_path = staticmethod(TransitionRouteGroupsClient.intent_path) + parse_intent_path = staticmethod(TransitionRouteGroupsClient.parse_intent_path) + page_path = staticmethod(TransitionRouteGroupsClient.page_path) + parse_page_path = staticmethod(TransitionRouteGroupsClient.parse_page_path) + transition_route_group_path = staticmethod(TransitionRouteGroupsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(TransitionRouteGroupsClient.parse_transition_route_group_path) + webhook_path = staticmethod(TransitionRouteGroupsClient.webhook_path) + parse_webhook_path = staticmethod(TransitionRouteGroupsClient.parse_webhook_path) + common_billing_account_path = staticmethod(TransitionRouteGroupsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TransitionRouteGroupsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TransitionRouteGroupsClient.common_folder_path) + parse_common_folder_path = staticmethod(TransitionRouteGroupsClient.parse_common_folder_path) + common_organization_path = staticmethod(TransitionRouteGroupsClient.common_organization_path) + parse_common_organization_path = staticmethod(TransitionRouteGroupsClient.parse_common_organization_path) + common_project_path = staticmethod(TransitionRouteGroupsClient.common_project_path) + parse_common_project_path = staticmethod(TransitionRouteGroupsClient.parse_common_project_path) + common_location_path = staticmethod(TransitionRouteGroupsClient.common_location_path) + parse_common_location_path = staticmethod(TransitionRouteGroupsClient.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: + TransitionRouteGroupsAsyncClient: The constructed client. + """ + return TransitionRouteGroupsClient.from_service_account_info.__func__(TransitionRouteGroupsAsyncClient, 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: + TransitionRouteGroupsAsyncClient: The constructed client. + """ + return TransitionRouteGroupsClient.from_service_account_file.__func__(TransitionRouteGroupsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> TransitionRouteGroupsTransport: + """Returns the transport used by the client instance. + + Returns: + TransitionRouteGroupsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(TransitionRouteGroupsClient).get_transport_class, type(TransitionRouteGroupsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, TransitionRouteGroupsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the transition route groups 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, ~.TransitionRouteGroupsTransport]): 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 = TransitionRouteGroupsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_transition_route_groups(self, + request: transition_route_group.ListTransitionRouteGroupsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransitionRouteGroupsAsyncPager: + r"""Returns the list of all transition route groups in + the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest`): + The request object. The request message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. + parent (:class:`str`): + Required. The flow to list all transition route groups + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.transition_route_groups.pagers.ListTransitionRouteGroupsAsyncPager: + The response message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. + + 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_transition_route_groups, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListTransitionRouteGroupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_transition_route_group(self, + request: transition_route_group.GetTransitionRouteGroupRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transition_route_group.TransitionRouteGroup: + r"""Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.GetTransitionRouteGroup]. + name (:class:`str`): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = transition_route_group.GetTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_transition_route_group(self, + request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, + *, + parent: str = None, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + in the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup]. + parent (:class:`str`): + Required. The flow to create an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + transition_route_group (:class:`google.cloud.dialogflowcx_v3.types.TransitionRouteGroup`): + Required. The transition route group + to create. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, transition_route_group]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if transition_route_group is not None: + request.transition_route_group = transition_route_group + + # 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_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_transition_route_group(self, + request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, + *, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.UpdateTransitionRouteGroup]. + transition_route_group (:class:`google.cloud.dialogflowcx_v3.types.TransitionRouteGroup`): + Required. The transition route group + to update. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([transition_route_group, 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 = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if transition_route_group is not None: + request.transition_route_group = transition_route_group + if update_mask is not None: + 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_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("transition_route_group.name", request.transition_route_group.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_transition_route_group(self, + request: transition_route_group.DeleteTransitionRouteGroupRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.DeleteTransitionRouteGroup]. + name (:class:`str`): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + to delete. Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = transition_route_group.DeleteTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TransitionRouteGroupsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py new file mode 100644 index 00000000..0eef6fe4 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/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.dialogflowcx_v3.services.transition_route_groups import pagers +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TransitionRouteGroupsGrpcTransport +from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport + + +class TransitionRouteGroupsClientMeta(type): + """Metaclass for the TransitionRouteGroups 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[TransitionRouteGroupsTransport]] + _transport_registry["grpc"] = TransitionRouteGroupsGrpcTransport + _transport_registry["grpc_asyncio"] = TransitionRouteGroupsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[TransitionRouteGroupsTransport]: + """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 TransitionRouteGroupsClient(metaclass=TransitionRouteGroupsClientMeta): + """Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + """ + + @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: + TransitionRouteGroupsClient: 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: + TransitionRouteGroupsClient: 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) -> TransitionRouteGroupsTransport: + """Returns the transport used by the client instance. + + Returns: + TransitionRouteGroupsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, TransitionRouteGroupsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the transition route groups 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, TransitionRouteGroupsTransport]): 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, TransitionRouteGroupsTransport): + # transport is a TransitionRouteGroupsTransport 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_transition_route_groups(self, + request: transition_route_group.ListTransitionRouteGroupsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransitionRouteGroupsPager: + r"""Returns the list of all transition route groups in + the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest): + The request object. The request message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. + parent (str): + Required. The flow to list all transition route groups + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.transition_route_groups.pagers.ListTransitionRouteGroupsPager: + The response message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. + + 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 transition_route_group.ListTransitionRouteGroupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, transition_route_group.ListTransitionRouteGroupsRequest): + request = transition_route_group.ListTransitionRouteGroupsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_transition_route_groups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListTransitionRouteGroupsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_transition_route_group(self, + request: transition_route_group.GetTransitionRouteGroupRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transition_route_group.TransitionRouteGroup: + r"""Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetTransitionRouteGroupRequest): + The request object. The request message for + [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.GetTransitionRouteGroup]. + name (str): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 transition_route_group.GetTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, transition_route_group.GetTransitionRouteGroupRequest): + request = transition_route_group.GetTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_transition_route_group] + + # Certain fields should be provided 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_transition_route_group(self, + request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, + *, + parent: str = None, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + in the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateTransitionRouteGroupRequest): + The request object. The request message for + [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup]. + parent (str): + Required. The flow to create an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + transition_route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): + Required. The transition route group + to create. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, transition_route_group]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_transition_route_group.CreateTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_transition_route_group.CreateTransitionRouteGroupRequest): + request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if transition_route_group is not None: + request.transition_route_group = transition_route_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_transition_route_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_transition_route_group(self, + request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, + *, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateTransitionRouteGroupRequest): + The request object. The request message for + [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.UpdateTransitionRouteGroup]. + transition_route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): + Required. The transition route group + to update. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.dialogflowcx_v3.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([transition_route_group, 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 gcdc_transition_route_group.UpdateTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): + request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if transition_route_group is not None: + request.transition_route_group = transition_route_group + if update_mask is not None: + 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_transition_route_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("transition_route_group.name", request.transition_route_group.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_transition_route_group(self, + request: transition_route_group.DeleteTransitionRouteGroupRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Args: + request (google.cloud.dialogflowcx_v3.types.DeleteTransitionRouteGroupRequest): + The request object. The request message for + [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.DeleteTransitionRouteGroup]. + name (str): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + to delete. Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 transition_route_group.DeleteTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, transition_route_group.DeleteTransitionRouteGroupRequest): + request = transition_route_group.DeleteTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_transition_route_group] + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TransitionRouteGroupsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py new file mode 100644 index 00000000..e14f7b04 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/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.dialogflowcx_v3.types import transition_route_group + + +class ListTransitionRouteGroupsPager: + """A pager for iterating through ``list_transition_route_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``transition_route_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTransitionRouteGroups`` requests and continue to iterate + through the ``transition_route_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` + 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[..., transition_route_group.ListTransitionRouteGroupsResponse], + request: transition_route_group.ListTransitionRouteGroupsRequest, + response: transition_route_group.ListTransitionRouteGroupsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse): + 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[transition_route_group.ListTransitionRouteGroupsResponse]: + 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[transition_route_group.TransitionRouteGroup]: + for page in self.pages: + yield from page.transition_route_groups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTransitionRouteGroupsAsyncPager: + """A pager for iterating through ``list_transition_route_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``transition_route_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTransitionRouteGroups`` requests and continue to iterate + through the ``transition_route_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` + 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[transition_route_group.ListTransitionRouteGroupsResponse]], + request: transition_route_group.ListTransitionRouteGroupsRequest, + response: transition_route_group.ListTransitionRouteGroupsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse): + 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[transition_route_group.ListTransitionRouteGroupsResponse]: + 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[transition_route_group.TransitionRouteGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.transition_route_groups: + 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/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py new file mode 100644 index 00000000..50e891f2 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/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 TransitionRouteGroupsTransport +from .grpc import TransitionRouteGroupsGrpcTransport +from .grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TransitionRouteGroupsTransport]] +_transport_registry['grpc'] = TransitionRouteGroupsGrpcTransport +_transport_registry['grpc_asyncio'] = TransitionRouteGroupsGrpcAsyncIOTransport + +__all__ = ( + 'TransitionRouteGroupsTransport', + 'TransitionRouteGroupsGrpcTransport', + 'TransitionRouteGroupsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py new file mode 100644 index 00000000..92e31a6b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/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.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class TransitionRouteGroupsTransport(abc.ABC): + """Abstract transport class for TransitionRouteGroups.""" + + 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_transition_route_groups: gapic_v1.method.wrap_method( + self.list_transition_route_groups, + default_timeout=None, + client_info=client_info, + ), + self.get_transition_route_group: gapic_v1.method.wrap_method( + self.get_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + self.create_transition_route_group: gapic_v1.method.wrap_method( + self.create_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + self.update_transition_route_group: gapic_v1.method.wrap_method( + self.update_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + self.delete_transition_route_group: gapic_v1.method.wrap_method( + self.delete_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_transition_route_groups(self) -> Callable[ + [transition_route_group.ListTransitionRouteGroupsRequest], + Union[ + transition_route_group.ListTransitionRouteGroupsResponse, + Awaitable[transition_route_group.ListTransitionRouteGroupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_transition_route_group(self) -> Callable[ + [transition_route_group.GetTransitionRouteGroupRequest], + Union[ + transition_route_group.TransitionRouteGroup, + Awaitable[transition_route_group.TransitionRouteGroup] + ]]: + raise NotImplementedError() + + @property + def create_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], + Union[ + gcdc_transition_route_group.TransitionRouteGroup, + Awaitable[gcdc_transition_route_group.TransitionRouteGroup] + ]]: + raise NotImplementedError() + + @property + def update_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], + Union[ + gcdc_transition_route_group.TransitionRouteGroup, + Awaitable[gcdc_transition_route_group.TransitionRouteGroup] + ]]: + raise NotImplementedError() + + @property + def delete_transition_route_group(self) -> Callable[ + [transition_route_group.DeleteTransitionRouteGroupRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'TransitionRouteGroupsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py new file mode 100644 index 00000000..4987008c --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/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.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import empty_pb2 # type: ignore +from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO + + +class TransitionRouteGroupsGrpcTransport(TransitionRouteGroupsTransport): + """gRPC backend transport for TransitionRouteGroups. + + Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + 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_transition_route_groups(self) -> Callable[ + [transition_route_group.ListTransitionRouteGroupsRequest], + transition_route_group.ListTransitionRouteGroupsResponse]: + r"""Return a callable for the list transition route groups method over gRPC. + + Returns the list of all transition route groups in + the specified flow. + + Returns: + Callable[[~.ListTransitionRouteGroupsRequest], + ~.ListTransitionRouteGroupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_transition_route_groups' not in self._stubs: + self._stubs['list_transition_route_groups'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/ListTransitionRouteGroups', + request_serializer=transition_route_group.ListTransitionRouteGroupsRequest.serialize, + response_deserializer=transition_route_group.ListTransitionRouteGroupsResponse.deserialize, + ) + return self._stubs['list_transition_route_groups'] + + @property + def get_transition_route_group(self) -> Callable[ + [transition_route_group.GetTransitionRouteGroupRequest], + transition_route_group.TransitionRouteGroup]: + r"""Return a callable for the get transition route group method over gRPC. + + Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Returns: + Callable[[~.GetTransitionRouteGroupRequest], + ~.TransitionRouteGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_transition_route_group' not in self._stubs: + self._stubs['get_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/GetTransitionRouteGroup', + request_serializer=transition_route_group.GetTransitionRouteGroupRequest.serialize, + response_deserializer=transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['get_transition_route_group'] + + @property + def create_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], + gcdc_transition_route_group.TransitionRouteGroup]: + r"""Return a callable for the create transition route group method over gRPC. + + Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + in the specified flow. + + Returns: + Callable[[~.CreateTransitionRouteGroupRequest], + ~.TransitionRouteGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: + self._stubs['create_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/CreateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.CreateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['create_transition_route_group'] + + @property + def update_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], + gcdc_transition_route_group.TransitionRouteGroup]: + r"""Return a callable for the update transition route group method over gRPC. + + Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Returns: + Callable[[~.UpdateTransitionRouteGroupRequest], + ~.TransitionRouteGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: + self._stubs['update_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/UpdateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['update_transition_route_group'] + + @property + def delete_transition_route_group(self) -> Callable[ + [transition_route_group.DeleteTransitionRouteGroupRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete transition route group method over gRPC. + + Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Returns: + Callable[[~.DeleteTransitionRouteGroupRequest], + ~.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_transition_route_group' not in self._stubs: + self._stubs['delete_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/DeleteTransitionRouteGroup', + request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transition_route_group'] + + +__all__ = ( + 'TransitionRouteGroupsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py new file mode 100644 index 00000000..ad065da6 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/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.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import empty_pb2 # type: ignore +from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO +from .grpc import TransitionRouteGroupsGrpcTransport + + +class TransitionRouteGroupsGrpcAsyncIOTransport(TransitionRouteGroupsTransport): + """gRPC AsyncIO backend transport for TransitionRouteGroups. + + Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + 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_transition_route_groups(self) -> Callable[ + [transition_route_group.ListTransitionRouteGroupsRequest], + Awaitable[transition_route_group.ListTransitionRouteGroupsResponse]]: + r"""Return a callable for the list transition route groups method over gRPC. + + Returns the list of all transition route groups in + the specified flow. + + Returns: + Callable[[~.ListTransitionRouteGroupsRequest], + Awaitable[~.ListTransitionRouteGroupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_transition_route_groups' not in self._stubs: + self._stubs['list_transition_route_groups'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/ListTransitionRouteGroups', + request_serializer=transition_route_group.ListTransitionRouteGroupsRequest.serialize, + response_deserializer=transition_route_group.ListTransitionRouteGroupsResponse.deserialize, + ) + return self._stubs['list_transition_route_groups'] + + @property + def get_transition_route_group(self) -> Callable[ + [transition_route_group.GetTransitionRouteGroupRequest], + Awaitable[transition_route_group.TransitionRouteGroup]]: + r"""Return a callable for the get transition route group method over gRPC. + + Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Returns: + Callable[[~.GetTransitionRouteGroupRequest], + Awaitable[~.TransitionRouteGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_transition_route_group' not in self._stubs: + self._stubs['get_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/GetTransitionRouteGroup', + request_serializer=transition_route_group.GetTransitionRouteGroupRequest.serialize, + response_deserializer=transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['get_transition_route_group'] + + @property + def create_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], + Awaitable[gcdc_transition_route_group.TransitionRouteGroup]]: + r"""Return a callable for the create transition route group method over gRPC. + + Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + in the specified flow. + + Returns: + Callable[[~.CreateTransitionRouteGroupRequest], + Awaitable[~.TransitionRouteGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: + self._stubs['create_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/CreateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.CreateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['create_transition_route_group'] + + @property + def update_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], + Awaitable[gcdc_transition_route_group.TransitionRouteGroup]]: + r"""Return a callable for the update transition route group method over gRPC. + + Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Returns: + Callable[[~.UpdateTransitionRouteGroupRequest], + Awaitable[~.TransitionRouteGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: + self._stubs['update_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/UpdateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['update_transition_route_group'] + + @property + def delete_transition_route_group(self) -> Callable[ + [transition_route_group.DeleteTransitionRouteGroupRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete transition route group method over gRPC. + + Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + + Returns: + Callable[[~.DeleteTransitionRouteGroupRequest], + 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_transition_route_group' not in self._stubs: + self._stubs['delete_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/DeleteTransitionRouteGroup', + request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transition_route_group'] + + +__all__ = ( + 'TransitionRouteGroupsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__init__.py new file mode 100644 index 00000000..630246bd --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py new file mode 100644 index 00000000..f89676b3 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py @@ -0,0 +1,687 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.versions import pagers +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport +from .client import VersionsClient + + +class VersionsAsyncClient: + """Service for managing + [Versions][google.cloud.dialogflow.cx.v3.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 in the specified + [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListVersionsRequest`): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. + parent (:class:`str`): + Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] + to list all versions for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.versions.pagers.ListVersionsAsyncPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3.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 + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetVersionRequest`): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.cx.v3.Versions.GetVersion]. + name (:class:`str`): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3.Version]. + Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity check: 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: gcdc_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcdc_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in + the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateVersionRequest`): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. + parent (:class:`str`): + Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] + to create an + [Version][google.cloud.dialogflow.cx.v3.Version] for. + Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (:class:`google.cloud.dialogflowcx_v3.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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.Version` + Represents a version of a flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = gcdc_version.CreateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcdc_version.Version, + metadata_type=gcdc_version.CreateVersionOperationMetadata, + ) + + # Done; return the response. + return response + + async def update_version(self, + request: gcdc_version.UpdateVersionRequest = None, + *, + version: gcdc_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]] = (), + ) -> gcdc_version.Version: + r"""Updates the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateVersionRequest`): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3.Versions.UpdateVersion]. + version (:class:`google.cloud.dialogflowcx_v3.types.Version`): + Required. The version to update. + 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. + Currently only ``description`` and ``display_name`` can + 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.dialogflowcx_v3.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = gcdc_version.UpdateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + if update_mask is not None: + 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"""Deletes the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteVersionRequest`): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3.Versions.DeleteVersion]. + name (:class:`str`): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3.Version] to + delete. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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, + ) + + async def load_version(self, + request: version.LoadVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Loads resources in the specified version to the draft + flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.LoadVersionRequest`): + The request object. The request message for + [Versions.LoadVersion][google.cloud.dialogflow.cx.v3.Versions.LoadVersion]. + name (:class:`str`): + Required. The + [Version][google.cloud.dialogflow.cx.v3.Version] to be + loaded to draft flow. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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 = version.LoadVersionRequest(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.load_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, + ) + + # 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py new file mode 100644 index 00000000..37c1918b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py @@ -0,0 +1,874 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.versions import pagers +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VersionsGrpcTransport +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport + + +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.cx.v3.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,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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 in the specified + [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListVersionsRequest): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. + parent (str): + Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] + to list all versions for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.versions.pagers.ListVersionsPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3.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 + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetVersionRequest): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.cx.v3.Versions.GetVersion]. + name (str): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3.Version]. + Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity check: 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: gcdc_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcdc_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in + the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateVersionRequest): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. + parent (str): + Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] + to create an + [Version][google.cloud.dialogflow.cx.v3.Version] for. + Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (google.cloud.dialogflowcx_v3.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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.Version` + Represents a version of a flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 gcdc_version.CreateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_version.CreateVersionRequest): + request = gcdc_version.CreateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcdc_version.Version, + metadata_type=gcdc_version.CreateVersionOperationMetadata, + ) + + # Done; return the response. + return response + + def update_version(self, + request: gcdc_version.UpdateVersionRequest = None, + *, + version: gcdc_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]] = (), + ) -> gcdc_version.Version: + r"""Updates the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateVersionRequest): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3.Versions.UpdateVersion]. + version (google.cloud.dialogflowcx_v3.types.Version): + Required. The version to update. + 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. + Currently only ``description`` and ``display_name`` can + 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.dialogflowcx_v3.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity 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 gcdc_version.UpdateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_version.UpdateVersionRequest): + request = gcdc_version.UpdateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + if update_mask is not None: + 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"""Deletes the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + Args: + request (google.cloud.dialogflowcx_v3.types.DeleteVersionRequest): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3.Versions.DeleteVersion]. + name (str): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3.Version] to + delete. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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, + ) + + def load_version(self, + request: version.LoadVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Loads resources in the specified version to the draft + flow. + + Args: + request (google.cloud.dialogflowcx_v3.types.LoadVersionRequest): + The request object. The request message for + [Versions.LoadVersion][google.cloud.dialogflow.cx.v3.Versions.LoadVersion]. + name (str): + Required. The + [Version][google.cloud.dialogflow.cx.v3.Version] to be + loaded to draft flow. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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 version.LoadVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.LoadVersionRequest): + request = version.LoadVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.load_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, + ) + + # 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/pagers.py new file mode 100644 index 00000000..1c20a2e4 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import version + + +class ListVersionsPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.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/v3/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py new file mode 100644 index 00000000..dfb70ce9 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.py new file mode 100644 index 00000000..b92ce225 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.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. +# +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.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +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-dialogflowcx', + ).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, + ), + self.load_version: gapic_v1.method.wrap_method( + self.load_version, + 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_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[ + [gcdc_version.CreateVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_version(self) -> Callable[ + [gcdc_version.UpdateVersionRequest], + Union[ + gcdc_version.Version, + Awaitable[gcdc_version.Version] + ]]: + raise NotImplementedError() + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def load_version(self) -> Callable[ + [version.LoadVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VersionsTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py new file mode 100644 index 00000000..62e44d60 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.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. +# +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.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +from google.longrunning import operations_pb2 # type: ignore +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.cx.v3.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] = {} + 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_versions(self) -> Callable[ + [version.ListVersionsRequest], + version.ListVersionsResponse]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions in the specified + [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + 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.cx.v3.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 + [Version][google.cloud.dialogflow.cx.v3.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.cx.v3.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcdc_version.CreateVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create version method over gRPC. + + Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in + the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + Returns: + Callable[[~.CreateVersionRequest], + ~.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_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/CreateVersion', + request_serializer=gcdc_version.CreateVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcdc_version.UpdateVersionRequest], + gcdc_version.Version]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + 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.cx.v3.Versions/UpdateVersion', + request_serializer=gcdc_version.UpdateVersionRequest.serialize, + response_deserializer=gcdc_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. + + Deletes the specified + [Version][google.cloud.dialogflow.cx.v3.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.cx.v3.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + @property + def load_version(self) -> Callable[ + [version.LoadVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the load version method over gRPC. + + Loads resources in the specified version to the draft + flow. + + Returns: + Callable[[~.LoadVersionRequest], + ~.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 'load_version' not in self._stubs: + self._stubs['load_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/LoadVersion', + request_serializer=version.LoadVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['load_version'] + + +__all__ = ( + 'VersionsGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py new file mode 100644 index 00000000..5a53e233 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py @@ -0,0 +1,410 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import VersionsGrpcTransport + + +class VersionsGrpcAsyncIOTransport(VersionsTransport): + """gRPC AsyncIO backend transport for Versions. + + Service for managing + [Versions][google.cloud.dialogflow.cx.v3.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] = {} + 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_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 in the specified + [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + 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.cx.v3.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 + [Version][google.cloud.dialogflow.cx.v3.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.cx.v3.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcdc_version.CreateVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create version method over gRPC. + + Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in + the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. + + Returns: + Callable[[~.CreateVersionRequest], + 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_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/CreateVersion', + request_serializer=gcdc_version.CreateVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcdc_version.UpdateVersionRequest], + Awaitable[gcdc_version.Version]]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified + [Version][google.cloud.dialogflow.cx.v3.Version]. + + 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.cx.v3.Versions/UpdateVersion', + request_serializer=gcdc_version.UpdateVersionRequest.serialize, + response_deserializer=gcdc_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. + + Deletes the specified + [Version][google.cloud.dialogflow.cx.v3.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.cx.v3.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + @property + def load_version(self) -> Callable[ + [version.LoadVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the load version method over gRPC. + + Loads resources in the specified version to the draft + flow. + + Returns: + Callable[[~.LoadVersionRequest], + 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 'load_version' not in self._stubs: + self._stubs['load_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Versions/LoadVersion', + request_serializer=version.LoadVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['load_version'] + + +__all__ = ( + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py new file mode 100644 index 00000000..8ace8262 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__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 WebhooksClient +from .async_client import WebhooksAsyncClient + +__all__ = ( + 'WebhooksClient', + 'WebhooksAsyncClient', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py new file mode 100644 index 00000000..d0bbe6dd --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py @@ -0,0 +1,581 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.webhooks import pagers +from google.cloud.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport +from .client import WebhooksClient + + +class WebhooksAsyncClient: + """Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. + """ + + _client: WebhooksClient + + DEFAULT_ENDPOINT = WebhooksClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WebhooksClient.DEFAULT_MTLS_ENDPOINT + + service_path = staticmethod(WebhooksClient.service_path) + parse_service_path = staticmethod(WebhooksClient.parse_service_path) + webhook_path = staticmethod(WebhooksClient.webhook_path) + parse_webhook_path = staticmethod(WebhooksClient.parse_webhook_path) + common_billing_account_path = staticmethod(WebhooksClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WebhooksClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WebhooksClient.common_folder_path) + parse_common_folder_path = staticmethod(WebhooksClient.parse_common_folder_path) + common_organization_path = staticmethod(WebhooksClient.common_organization_path) + parse_common_organization_path = staticmethod(WebhooksClient.parse_common_organization_path) + common_project_path = staticmethod(WebhooksClient.common_project_path) + parse_common_project_path = staticmethod(WebhooksClient.parse_common_project_path) + common_location_path = staticmethod(WebhooksClient.common_location_path) + parse_common_location_path = staticmethod(WebhooksClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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: + WebhooksAsyncClient: The constructed client. + """ + return WebhooksClient.from_service_account_info.__func__(WebhooksAsyncClient, 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: + WebhooksAsyncClient: The constructed client. + """ + return WebhooksClient.from_service_account_file.__func__(WebhooksAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WebhooksTransport: + """Returns the transport used by the client instance. + + Returns: + WebhooksTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(WebhooksClient).get_transport_class, type(WebhooksClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, WebhooksTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the webhooks 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, ~.WebhooksTransport]): 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 = WebhooksClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_webhooks(self, + request: webhook.ListWebhooksRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWebhooksAsyncPager: + r"""Returns the list of all webhooks in the specified + agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ListWebhooksRequest`): + The request object. The request message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. + parent (:class:`str`): + Required. The agent to list all webhooks for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.webhooks.pagers.ListWebhooksAsyncPager: + The response message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. + + 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 = webhook.ListWebhooksRequest(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_webhooks, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListWebhooksAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_webhook(self, + request: webhook.GetWebhookRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> webhook.Webhook: + r"""Retrieves the specified webhook. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.GetWebhookRequest`): + The request object. The request message for + [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3.Webhooks.GetWebhook]. + name (:class:`str`): + Required. The name of the webhook. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = webhook.GetWebhookRequest(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_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_webhook(self, + request: gcdc_webhook.CreateWebhookRequest = None, + *, + parent: str = None, + webhook: gcdc_webhook.Webhook = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Creates a webhook in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.CreateWebhookRequest`): + The request object. The request message for + [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook]. + parent (:class:`str`): + Required. The agent to create a webhook for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + webhook (:class:`google.cloud.dialogflowcx_v3.types.Webhook`): + Required. The webhook to create. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, webhook]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_webhook.CreateWebhookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if webhook is not None: + request.webhook = webhook + + # 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_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_webhook(self, + request: gcdc_webhook.UpdateWebhookRequest = None, + *, + webhook: gcdc_webhook.Webhook = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Updates the specified webhook. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.UpdateWebhookRequest`): + The request object. The request message for + [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook]. + webhook (:class:`google.cloud.dialogflowcx_v3.types.Webhook`): + Required. The webhook to update. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([webhook, 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 = gcdc_webhook.UpdateWebhookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if webhook is not None: + request.webhook = webhook + if update_mask is not None: + 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_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("webhook.name", request.webhook.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_webhook(self, + request: webhook.DeleteWebhookRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified webhook. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.DeleteWebhookRequest`): + The request object. The request message for + [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3.Webhooks.DeleteWebhook]. + name (:class:`str`): + Required. The name of the webhook to delete. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = webhook.DeleteWebhookRequest(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_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebhooksAsyncClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py new file mode 100644 index 00000000..564ed5ab --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py @@ -0,0 +1,777 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.webhooks import pagers +from google.cloud.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WebhooksGrpcTransport +from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport + + +class WebhooksClientMeta(type): + """Metaclass for the Webhooks 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[WebhooksTransport]] + _transport_registry["grpc"] = WebhooksGrpcTransport + _transport_registry["grpc_asyncio"] = WebhooksGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[WebhooksTransport]: + """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 WebhooksClient(metaclass=WebhooksClientMeta): + """Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. + """ + + @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: + WebhooksClient: 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: + WebhooksClient: 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) -> WebhooksTransport: + """Returns the transport used by the client instance. + + Returns: + WebhooksTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def service_path(project: str,location: str,namespace: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, WebhooksTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the webhooks 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, WebhooksTransport]): 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, WebhooksTransport): + # transport is a WebhooksTransport 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_webhooks(self, + request: webhook.ListWebhooksRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWebhooksPager: + r"""Returns the list of all webhooks in the specified + agent. + + Args: + request (google.cloud.dialogflowcx_v3.types.ListWebhooksRequest): + The request object. The request message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. + parent (str): + Required. The agent to list all webhooks for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.services.webhooks.pagers.ListWebhooksPager: + The response message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. + + 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 webhook.ListWebhooksRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, webhook.ListWebhooksRequest): + request = webhook.ListWebhooksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_webhooks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListWebhooksPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_webhook(self, + request: webhook.GetWebhookRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> webhook.Webhook: + r"""Retrieves the specified webhook. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetWebhookRequest): + The request object. The request message for + [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3.Webhooks.GetWebhook]. + name (str): + Required. The name of the webhook. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 webhook.GetWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, webhook.GetWebhookRequest): + request = webhook.GetWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_webhook] + + # Certain fields should be provided 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_webhook(self, + request: gcdc_webhook.CreateWebhookRequest = None, + *, + parent: str = None, + webhook: gcdc_webhook.Webhook = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Creates a webhook in the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3.types.CreateWebhookRequest): + The request object. The request message for + [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook]. + parent (str): + Required. The agent to create a webhook for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + webhook (google.cloud.dialogflowcx_v3.types.Webhook): + Required. The webhook to create. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, webhook]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_webhook.CreateWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_webhook.CreateWebhookRequest): + request = gcdc_webhook.CreateWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if webhook is not None: + request.webhook = webhook + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_webhook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_webhook(self, + request: gcdc_webhook.UpdateWebhookRequest = None, + *, + webhook: gcdc_webhook.Webhook = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Updates the specified webhook. + + Args: + request (google.cloud.dialogflowcx_v3.types.UpdateWebhookRequest): + The request object. The request message for + [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook]. + webhook (google.cloud.dialogflowcx_v3.types.Webhook): + Required. The webhook to update. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.dialogflowcx_v3.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([webhook, 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 gcdc_webhook.UpdateWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_webhook.UpdateWebhookRequest): + request = gcdc_webhook.UpdateWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if webhook is not None: + request.webhook = webhook + if update_mask is not None: + 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_webhook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("webhook.name", request.webhook.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_webhook(self, + request: webhook.DeleteWebhookRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified webhook. + + Args: + request (google.cloud.dialogflowcx_v3.types.DeleteWebhookRequest): + The request object. The request message for + [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3.Webhooks.DeleteWebhook]. + name (str): + Required. The name of the webhook to delete. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 webhook.DeleteWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, webhook.DeleteWebhookRequest): + request = webhook.DeleteWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_webhook] + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebhooksClient", +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py new file mode 100644 index 00000000..5c10e717 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/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.dialogflowcx_v3.types import webhook + + +class ListWebhooksPager: + """A pager for iterating through ``list_webhooks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``webhooks`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWebhooks`` requests and continue to iterate + through the ``webhooks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` + 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[..., webhook.ListWebhooksResponse], + request: webhook.ListWebhooksRequest, + response: webhook.ListWebhooksResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListWebhooksRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListWebhooksResponse): + 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 = webhook.ListWebhooksRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[webhook.ListWebhooksResponse]: + 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[webhook.Webhook]: + for page in self.pages: + yield from page.webhooks + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWebhooksAsyncPager: + """A pager for iterating through ``list_webhooks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``webhooks`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWebhooks`` requests and continue to iterate + through the ``webhooks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` + 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[webhook.ListWebhooksResponse]], + request: webhook.ListWebhooksRequest, + response: webhook.ListWebhooksResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3.types.ListWebhooksRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3.types.ListWebhooksResponse): + 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 = webhook.ListWebhooksRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[webhook.ListWebhooksResponse]: + 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[webhook.Webhook]: + async def async_generator(): + async for page in self.pages: + for response in page.webhooks: + 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/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py new file mode 100644 index 00000000..6006a6e7 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/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 WebhooksTransport +from .grpc import WebhooksGrpcTransport +from .grpc_asyncio import WebhooksGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WebhooksTransport]] +_transport_registry['grpc'] = WebhooksGrpcTransport +_transport_registry['grpc_asyncio'] = WebhooksGrpcAsyncIOTransport + +__all__ = ( + 'WebhooksTransport', + 'WebhooksGrpcTransport', + 'WebhooksGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py new file mode 100644 index 00000000..65512411 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/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.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +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-dialogflowcx', + ).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 WebhooksTransport(abc.ABC): + """Abstract transport class for Webhooks.""" + + 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_webhooks: gapic_v1.method.wrap_method( + self.list_webhooks, + default_timeout=None, + client_info=client_info, + ), + self.get_webhook: gapic_v1.method.wrap_method( + self.get_webhook, + default_timeout=None, + client_info=client_info, + ), + self.create_webhook: gapic_v1.method.wrap_method( + self.create_webhook, + default_timeout=None, + client_info=client_info, + ), + self.update_webhook: gapic_v1.method.wrap_method( + self.update_webhook, + default_timeout=None, + client_info=client_info, + ), + self.delete_webhook: gapic_v1.method.wrap_method( + self.delete_webhook, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_webhooks(self) -> Callable[ + [webhook.ListWebhooksRequest], + Union[ + webhook.ListWebhooksResponse, + Awaitable[webhook.ListWebhooksResponse] + ]]: + raise NotImplementedError() + + @property + def get_webhook(self) -> Callable[ + [webhook.GetWebhookRequest], + Union[ + webhook.Webhook, + Awaitable[webhook.Webhook] + ]]: + raise NotImplementedError() + + @property + def create_webhook(self) -> Callable[ + [gcdc_webhook.CreateWebhookRequest], + Union[ + gcdc_webhook.Webhook, + Awaitable[gcdc_webhook.Webhook] + ]]: + raise NotImplementedError() + + @property + def update_webhook(self) -> Callable[ + [gcdc_webhook.UpdateWebhookRequest], + Union[ + gcdc_webhook.Webhook, + Awaitable[gcdc_webhook.Webhook] + ]]: + raise NotImplementedError() + + @property + def delete_webhook(self) -> Callable[ + [webhook.DeleteWebhookRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'WebhooksTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py new file mode 100644 index 00000000..34c40fc6 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/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.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +from google.protobuf import empty_pb2 # type: ignore +from .base import WebhooksTransport, DEFAULT_CLIENT_INFO + + +class WebhooksGrpcTransport(WebhooksTransport): + """gRPC backend transport for Webhooks. + + Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. + + 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_webhooks(self) -> Callable[ + [webhook.ListWebhooksRequest], + webhook.ListWebhooksResponse]: + r"""Return a callable for the list webhooks method over gRPC. + + Returns the list of all webhooks in the specified + agent. + + Returns: + Callable[[~.ListWebhooksRequest], + ~.ListWebhooksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_webhooks' not in self._stubs: + self._stubs['list_webhooks'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/ListWebhooks', + request_serializer=webhook.ListWebhooksRequest.serialize, + response_deserializer=webhook.ListWebhooksResponse.deserialize, + ) + return self._stubs['list_webhooks'] + + @property + def get_webhook(self) -> Callable[ + [webhook.GetWebhookRequest], + webhook.Webhook]: + r"""Return a callable for the get webhook method over gRPC. + + Retrieves the specified webhook. + + Returns: + Callable[[~.GetWebhookRequest], + ~.Webhook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_webhook' not in self._stubs: + self._stubs['get_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/GetWebhook', + request_serializer=webhook.GetWebhookRequest.serialize, + response_deserializer=webhook.Webhook.deserialize, + ) + return self._stubs['get_webhook'] + + @property + def create_webhook(self) -> Callable[ + [gcdc_webhook.CreateWebhookRequest], + gcdc_webhook.Webhook]: + r"""Return a callable for the create webhook method over gRPC. + + Creates a webhook in the specified agent. + + Returns: + Callable[[~.CreateWebhookRequest], + ~.Webhook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_webhook' not in self._stubs: + self._stubs['create_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/CreateWebhook', + request_serializer=gcdc_webhook.CreateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['create_webhook'] + + @property + def update_webhook(self) -> Callable[ + [gcdc_webhook.UpdateWebhookRequest], + gcdc_webhook.Webhook]: + r"""Return a callable for the update webhook method over gRPC. + + Updates the specified webhook. + + Returns: + Callable[[~.UpdateWebhookRequest], + ~.Webhook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_webhook' not in self._stubs: + self._stubs['update_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/UpdateWebhook', + request_serializer=gcdc_webhook.UpdateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['update_webhook'] + + @property + def delete_webhook(self) -> Callable[ + [webhook.DeleteWebhookRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete webhook method over gRPC. + + Deletes the specified webhook. + + Returns: + Callable[[~.DeleteWebhookRequest], + ~.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_webhook' not in self._stubs: + self._stubs['delete_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/DeleteWebhook', + request_serializer=webhook.DeleteWebhookRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_webhook'] + + +__all__ = ( + 'WebhooksGrpcTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py new file mode 100644 index 00000000..83099cd0 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/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.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +from google.protobuf import empty_pb2 # type: ignore +from .base import WebhooksTransport, DEFAULT_CLIENT_INFO +from .grpc import WebhooksGrpcTransport + + +class WebhooksGrpcAsyncIOTransport(WebhooksTransport): + """gRPC AsyncIO backend transport for Webhooks. + + Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. + + 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_webhooks(self) -> Callable[ + [webhook.ListWebhooksRequest], + Awaitable[webhook.ListWebhooksResponse]]: + r"""Return a callable for the list webhooks method over gRPC. + + Returns the list of all webhooks in the specified + agent. + + Returns: + Callable[[~.ListWebhooksRequest], + Awaitable[~.ListWebhooksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_webhooks' not in self._stubs: + self._stubs['list_webhooks'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/ListWebhooks', + request_serializer=webhook.ListWebhooksRequest.serialize, + response_deserializer=webhook.ListWebhooksResponse.deserialize, + ) + return self._stubs['list_webhooks'] + + @property + def get_webhook(self) -> Callable[ + [webhook.GetWebhookRequest], + Awaitable[webhook.Webhook]]: + r"""Return a callable for the get webhook method over gRPC. + + Retrieves the specified webhook. + + Returns: + Callable[[~.GetWebhookRequest], + Awaitable[~.Webhook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_webhook' not in self._stubs: + self._stubs['get_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/GetWebhook', + request_serializer=webhook.GetWebhookRequest.serialize, + response_deserializer=webhook.Webhook.deserialize, + ) + return self._stubs['get_webhook'] + + @property + def create_webhook(self) -> Callable[ + [gcdc_webhook.CreateWebhookRequest], + Awaitable[gcdc_webhook.Webhook]]: + r"""Return a callable for the create webhook method over gRPC. + + Creates a webhook in the specified agent. + + Returns: + Callable[[~.CreateWebhookRequest], + Awaitable[~.Webhook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_webhook' not in self._stubs: + self._stubs['create_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/CreateWebhook', + request_serializer=gcdc_webhook.CreateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['create_webhook'] + + @property + def update_webhook(self) -> Callable[ + [gcdc_webhook.UpdateWebhookRequest], + Awaitable[gcdc_webhook.Webhook]]: + r"""Return a callable for the update webhook method over gRPC. + + Updates the specified webhook. + + Returns: + Callable[[~.UpdateWebhookRequest], + Awaitable[~.Webhook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_webhook' not in self._stubs: + self._stubs['update_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/UpdateWebhook', + request_serializer=gcdc_webhook.UpdateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['update_webhook'] + + @property + def delete_webhook(self) -> Callable[ + [webhook.DeleteWebhookRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete webhook method over gRPC. + + Deletes the specified webhook. + + Returns: + Callable[[~.DeleteWebhookRequest], + 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_webhook' not in self._stubs: + self._stubs['delete_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3.Webhooks/DeleteWebhook', + request_serializer=webhook.DeleteWebhookRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_webhook'] + + +__all__ = ( + 'WebhooksGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.py new file mode 100644 index 00000000..98d63df7 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.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. +# +from .agent import ( + Agent, + AgentValidationResult, + CreateAgentRequest, + DeleteAgentRequest, + ExportAgentRequest, + ExportAgentResponse, + GetAgentRequest, + GetAgentValidationResultRequest, + ListAgentsRequest, + ListAgentsResponse, + RestoreAgentRequest, + SpeechToTextSettings, + UpdateAgentRequest, + ValidateAgentRequest, +) +from .audio_config import ( + InputAudioConfig, + OutputAudioConfig, + SpeechWordInfo, + SynthesizeSpeechConfig, + VoiceSelectionParams, + AudioEncoding, + OutputAudioEncoding, + SpeechModelVariant, + SsmlVoiceGender, +) +from .entity_type import ( + CreateEntityTypeRequest, + DeleteEntityTypeRequest, + EntityType, + GetEntityTypeRequest, + ListEntityTypesRequest, + ListEntityTypesResponse, + UpdateEntityTypeRequest, +) +from .environment import ( + CreateEnvironmentRequest, + DeleteEnvironmentRequest, + Environment, + GetEnvironmentRequest, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + LookupEnvironmentHistoryRequest, + LookupEnvironmentHistoryResponse, + UpdateEnvironmentRequest, +) +from .experiment import ( + CreateExperimentRequest, + DeleteExperimentRequest, + Experiment, + GetExperimentRequest, + ListExperimentsRequest, + ListExperimentsResponse, + StartExperimentRequest, + StopExperimentRequest, + UpdateExperimentRequest, + VariantsHistory, + VersionVariants, +) +from .flow import ( + CreateFlowRequest, + DeleteFlowRequest, + ExportFlowRequest, + ExportFlowResponse, + Flow, + FlowValidationResult, + GetFlowRequest, + GetFlowValidationResultRequest, + ImportFlowRequest, + ImportFlowResponse, + ListFlowsRequest, + ListFlowsResponse, + NluSettings, + TrainFlowRequest, + UpdateFlowRequest, + ValidateFlowRequest, +) +from .fulfillment import ( + Fulfillment, +) +from .intent import ( + CreateIntentRequest, + DeleteIntentRequest, + GetIntentRequest, + Intent, + ListIntentsRequest, + ListIntentsResponse, + UpdateIntentRequest, + IntentView, +) +from .page import ( + CreatePageRequest, + DeletePageRequest, + EventHandler, + Form, + GetPageRequest, + ListPagesRequest, + ListPagesResponse, + Page, + TransitionRoute, + UpdatePageRequest, +) +from .response_message import ( + ResponseMessage, +) +from .security_settings import ( + CreateSecuritySettingsRequest, + DeleteSecuritySettingsRequest, + GetSecuritySettingsRequest, + ListSecuritySettingsRequest, + ListSecuritySettingsResponse, + SecuritySettings, + UpdateSecuritySettingsRequest, +) +from .session import ( + AudioInput, + DetectIntentRequest, + DetectIntentResponse, + DtmfInput, + EventInput, + FulfillIntentRequest, + FulfillIntentResponse, + IntentInput, + Match, + MatchIntentRequest, + MatchIntentResponse, + QueryInput, + QueryParameters, + QueryResult, + SentimentAnalysisResult, + StreamingDetectIntentRequest, + StreamingDetectIntentResponse, + StreamingRecognitionResult, + TextInput, +) +from .session_entity_type import ( + CreateSessionEntityTypeRequest, + DeleteSessionEntityTypeRequest, + GetSessionEntityTypeRequest, + ListSessionEntityTypesRequest, + ListSessionEntityTypesResponse, + SessionEntityType, + UpdateSessionEntityTypeRequest, +) +from .test_case import ( + BatchDeleteTestCasesRequest, + BatchRunTestCasesMetadata, + BatchRunTestCasesRequest, + BatchRunTestCasesResponse, + CalculateCoverageRequest, + CalculateCoverageResponse, + ConversationTurn, + CreateTestCaseRequest, + ExportTestCasesMetadata, + ExportTestCasesRequest, + ExportTestCasesResponse, + GetTestCaseRequest, + GetTestCaseResultRequest, + ImportTestCasesMetadata, + ImportTestCasesRequest, + ImportTestCasesResponse, + IntentCoverage, + ListTestCaseResultsRequest, + ListTestCaseResultsResponse, + ListTestCasesRequest, + ListTestCasesResponse, + RunTestCaseMetadata, + RunTestCaseRequest, + RunTestCaseResponse, + TestCase, + TestCaseError, + TestCaseResult, + TestConfig, + TestError, + TestRunDifference, + TransitionCoverage, + TransitionRouteGroupCoverage, + UpdateTestCaseRequest, + TestResult, +) +from .transition_route_group import ( + CreateTransitionRouteGroupRequest, + DeleteTransitionRouteGroupRequest, + GetTransitionRouteGroupRequest, + ListTransitionRouteGroupsRequest, + ListTransitionRouteGroupsResponse, + TransitionRouteGroup, + UpdateTransitionRouteGroupRequest, +) +from .validation_message import ( + ResourceName, + ValidationMessage, +) +from .version import ( + CreateVersionOperationMetadata, + CreateVersionRequest, + DeleteVersionRequest, + GetVersionRequest, + ListVersionsRequest, + ListVersionsResponse, + LoadVersionRequest, + UpdateVersionRequest, + Version, +) +from .webhook import ( + CreateWebhookRequest, + DeleteWebhookRequest, + GetWebhookRequest, + ListWebhooksRequest, + ListWebhooksResponse, + PageInfo, + SessionInfo, + UpdateWebhookRequest, + Webhook, + WebhookRequest, + WebhookResponse, +) + +__all__ = ( + 'Agent', + 'AgentValidationResult', + 'CreateAgentRequest', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'GetAgentRequest', + 'GetAgentValidationResultRequest', + 'ListAgentsRequest', + 'ListAgentsResponse', + 'RestoreAgentRequest', + 'SpeechToTextSettings', + 'UpdateAgentRequest', + 'ValidateAgentRequest', + 'InputAudioConfig', + 'OutputAudioConfig', + 'SpeechWordInfo', + 'SynthesizeSpeechConfig', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'Environment', + 'GetEnvironmentRequest', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LookupEnvironmentHistoryRequest', + 'LookupEnvironmentHistoryResponse', + 'UpdateEnvironmentRequest', + 'CreateExperimentRequest', + 'DeleteExperimentRequest', + 'Experiment', + 'GetExperimentRequest', + 'ListExperimentsRequest', + 'ListExperimentsResponse', + 'StartExperimentRequest', + 'StopExperimentRequest', + 'UpdateExperimentRequest', + 'VariantsHistory', + 'VersionVariants', + 'CreateFlowRequest', + 'DeleteFlowRequest', + 'ExportFlowRequest', + 'ExportFlowResponse', + 'Flow', + 'FlowValidationResult', + 'GetFlowRequest', + 'GetFlowValidationResultRequest', + 'ImportFlowRequest', + 'ImportFlowResponse', + 'ListFlowsRequest', + 'ListFlowsResponse', + 'NluSettings', + 'TrainFlowRequest', + 'UpdateFlowRequest', + 'ValidateFlowRequest', + 'Fulfillment', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreatePageRequest', + 'DeletePageRequest', + 'EventHandler', + 'Form', + 'GetPageRequest', + 'ListPagesRequest', + 'ListPagesResponse', + 'Page', + 'TransitionRoute', + 'UpdatePageRequest', + 'ResponseMessage', + 'CreateSecuritySettingsRequest', + 'DeleteSecuritySettingsRequest', + 'GetSecuritySettingsRequest', + 'ListSecuritySettingsRequest', + 'ListSecuritySettingsResponse', + 'SecuritySettings', + 'UpdateSecuritySettingsRequest', + 'AudioInput', + 'DetectIntentRequest', + 'DetectIntentResponse', + 'DtmfInput', + 'EventInput', + 'FulfillIntentRequest', + 'FulfillIntentResponse', + 'IntentInput', + 'Match', + 'MatchIntentRequest', + 'MatchIntentResponse', + 'QueryInput', + 'QueryParameters', + 'QueryResult', + 'SentimentAnalysisResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'CreateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + 'GetSessionEntityTypeRequest', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'SessionEntityType', + 'UpdateSessionEntityTypeRequest', + 'BatchDeleteTestCasesRequest', + 'BatchRunTestCasesMetadata', + 'BatchRunTestCasesRequest', + 'BatchRunTestCasesResponse', + 'CalculateCoverageRequest', + 'CalculateCoverageResponse', + 'ConversationTurn', + 'CreateTestCaseRequest', + 'ExportTestCasesMetadata', + 'ExportTestCasesRequest', + 'ExportTestCasesResponse', + 'GetTestCaseRequest', + 'GetTestCaseResultRequest', + 'ImportTestCasesMetadata', + 'ImportTestCasesRequest', + 'ImportTestCasesResponse', + 'IntentCoverage', + 'ListTestCaseResultsRequest', + 'ListTestCaseResultsResponse', + 'ListTestCasesRequest', + 'ListTestCasesResponse', + 'RunTestCaseMetadata', + 'RunTestCaseRequest', + 'RunTestCaseResponse', + 'TestCase', + 'TestCaseError', + 'TestCaseResult', + 'TestConfig', + 'TestError', + 'TestRunDifference', + 'TransitionCoverage', + 'TransitionRouteGroupCoverage', + 'UpdateTestCaseRequest', + 'TestResult', + 'CreateTransitionRouteGroupRequest', + 'DeleteTransitionRouteGroupRequest', + 'GetTransitionRouteGroupRequest', + 'ListTransitionRouteGroupsRequest', + 'ListTransitionRouteGroupsResponse', + 'TransitionRouteGroup', + 'UpdateTransitionRouteGroupRequest', + 'ResourceName', + 'ValidationMessage', + 'CreateVersionOperationMetadata', + 'CreateVersionRequest', + 'DeleteVersionRequest', + 'GetVersionRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'LoadVersionRequest', + 'UpdateVersionRequest', + 'Version', + 'CreateWebhookRequest', + 'DeleteWebhookRequest', + 'GetWebhookRequest', + 'ListWebhooksRequest', + 'ListWebhooksResponse', + 'PageInfo', + 'SessionInfo', + 'UpdateWebhookRequest', + 'Webhook', + 'WebhookRequest', + 'WebhookResponse', +) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py new file mode 100644 index 00000000..67a58714 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py @@ -0,0 +1,491 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import flow +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'SpeechToTextSettings', + 'Agent', + 'ListAgentsRequest', + 'ListAgentsResponse', + 'GetAgentRequest', + 'CreateAgentRequest', + 'UpdateAgentRequest', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'RestoreAgentRequest', + 'ValidateAgentRequest', + 'GetAgentValidationResultRequest', + 'AgentValidationResult', + }, +) + + +class SpeechToTextSettings(proto.Message): + r"""Settings related to speech recognition. + Attributes: + enable_speech_adaptation (bool): + Whether to use speech adaptation for speech + recognition. + """ + + enable_speech_adaptation = proto.Field( + proto.BOOL, + number=1, + ) + + +class Agent(proto.Message): + r"""Agents are best described as Natural Language Understanding (NLU) + modules that transform user requests into actionable data. You can + include agents in your app, product, or service to determine user + intent and respond to the user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3.Intent], [Entity + Types][google.cloud.dialogflow.cx.v3.EntityType], + [Flows][google.cloud.dialogflow.cx.v3.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], and so on to + manage the conversation flows.. + + Attributes: + name (str): + The unique identifier of the agent. Required for the + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent] + method. + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent] + populates the name automatically. Format: + ``projects//locations//agents/``. + display_name (str): + Required. The human-readable name of the + agent, unique within the location. + default_language_code (str): + Immutable. 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 + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent] + method. + supported_language_codes (Sequence[str]): + The list of all languages supported by the agent (except for + the ``default_language_code``). + time_zone (str): + Required. The time zone of the agent from the `time zone + database `__, e.g., + America/New_York, Europe/Paris. + description (str): + The description of the agent. The maximum + length is 500 characters. If exceeded, the + request is rejected. + avatar_uri (str): + The URI of the agent's avatar. Avatars are used throughout + the Dialogflow console and in the self-hosted `Web + Demo `__ + integration. + speech_to_text_settings (google.cloud.dialogflowcx_v3.types.SpeechToTextSettings): + Speech recognition related settings. + start_flow (str): + Immutable. Name of the start flow in this agent. A start + flow will be automatically created when the agent is + created, and can only be deleted by deleting the agent. + Format: + ``projects//locations//agents//flows/``. + security_settings (str): + Name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + reference for the agent. Format: + ``projects//locations//securitySettings/``. + enable_stackdriver_logging (bool): + Indicates if stackdriver logging is enabled + for the agent. + enable_spell_correction (bool): + Indicates if automatic spell correction is + enabled in detect intent requests. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + default_language_code = proto.Field( + proto.STRING, + number=3, + ) + supported_language_codes = proto.RepeatedField( + proto.STRING, + number=4, + ) + time_zone = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + avatar_uri = proto.Field( + proto.STRING, + number=7, + ) + speech_to_text_settings = proto.Field( + proto.MESSAGE, + number=13, + message='SpeechToTextSettings', + ) + start_flow = proto.Field( + proto.STRING, + number=16, + ) + security_settings = proto.Field( + proto.STRING, + number=17, + ) + enable_stackdriver_logging = proto.Field( + proto.BOOL, + number=18, + ) + enable_spell_correction = proto.Field( + proto.BOOL, + number=20, + ) + + +class ListAgentsRequest(proto.Message): + r"""The request message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + + Attributes: + parent (str): + Required. The location to list all agents for. 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 ListAgentsResponse(proto.Message): + r"""The response message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. + + Attributes: + agents (Sequence[google.cloud.dialogflowcx_v3.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 GetAgentRequest(proto.Message): + r"""The request message for + [Agents.GetAgent][google.cloud.dialogflow.cx.v3.Agents.GetAgent]. + + Attributes: + name (str): + Required. The name of the agent. Format: + ``projects//locations//agents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAgentRequest(proto.Message): + r"""The request message for + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent]. + + Attributes: + parent (str): + Required. The location to create a agent for. Format: + ``projects//locations/``. + agent (google.cloud.dialogflowcx_v3.types.Agent): + Required. The agent to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent = proto.Field( + proto.MESSAGE, + number=2, + message='Agent', + ) + + +class UpdateAgentRequest(proto.Message): + r"""The request message for + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent]. + + Attributes: + agent (google.cloud.dialogflowcx_v3.types.Agent): + Required. The agent to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + 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.cx.v3.Agents.DeleteAgent]. + + Attributes: + name (str): + Required. The name of the agent to delete. Format: + ``projects//locations//agents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportAgentRequest(proto.Message): + r"""The request message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. + + Attributes: + name (str): + Required. The name of the agent to export. Format: + ``projects//locations//agents/``. + 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. + environment (str): + Optional. Environment name. If not set, draft environment is + assumed. Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + ) + environment = proto.Field( + proto.STRING, + number=5, + ) + + +class ExportAgentResponse(proto.Message): + r"""The response message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.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][google.cloud.dialogflow.cx.v3.ExportAgentRequest]. + agent_content (bytes): + Uncompressed raw byte content for agent. + """ + + agent_uri = proto.Field( + proto.STRING, + number=1, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=2, + oneof='agent', + ) + + +class RestoreAgentRequest(proto.Message): + r"""The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. + + Attributes: + name (str): + Required. The name of the agent to restore into. Format: + ``projects//locations//agents/``. + agent_uri (str): + The `Google Cloud + Storage `__ URI to + restore agent from. The format of this URI must be + ``gs:///``. + agent_content (bytes): + Uncompressed raw byte content for agent. + restore_option (google.cloud.dialogflowcx_v3.types.RestoreAgentRequest.RestoreOption): + Agent restore mode. If not specified, ``KEEP`` is assumed. + """ + class RestoreOption(proto.Enum): + r"""Restore option.""" + RESTORE_OPTION_UNSPECIFIED = 0 + KEEP = 1 + FALLBACK = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + restore_option = proto.Field( + proto.ENUM, + number=5, + enum=RestoreOption, + ) + + +class ValidateAgentRequest(proto.Message): + r"""The request message for + [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3.Agents.ValidateAgent]. + + Attributes: + name (str): + Required. The agent to validate. Format: + ``projects//locations//agents/``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAgentValidationResultRequest(proto.Message): + r"""The request message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + Attributes: + name (str): + Required. The agent name. Format: + ``projects//locations//agents//validationResult``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class AgentValidationResult(proto.Message): + r"""The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. + + Attributes: + name (str): + The unique identifier of the agent validation result. + Format: + ``projects//locations//agents//validationResult``. + flow_validation_results (Sequence[google.cloud.dialogflowcx_v3.types.FlowValidationResult]): + Contains all flow validation results. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + flow_validation_results = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=flow.FlowValidationResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.py new file mode 100644 index 00000000..79422752 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.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 proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'AudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'OutputAudioEncoding', + 'SpeechWordInfo', + 'InputAudioConfig', + 'VoiceSelectionParams', + 'SynthesizeSpeechConfig', + 'OutputAudioConfig', + }, +) + + +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.cx.v3.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 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.dialogflowcx_v3.types.AudioEncoding): + Required. Audio encoding of the audio content + to process. + sample_rate_hertz (int): + Sample rate (in Hertz) of the audio content sent in the + query. Refer to `Cloud Speech API + documentation `__ + for more details. + enable_word_info (bool): + Optional. If ``true``, Dialogflow returns + [SpeechWordInfo][google.cloud.dialogflow.cx.v3.SpeechWordInfo] + in + [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3.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]): + Optional. 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. + model (str): + Optional. 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.dialogflowcx_v3.types.SpeechModelVariant): + Optional. Which variant of the [Speech + model][google.cloud.dialogflow.cx.v3.InputAudioConfig.model] + to use. + single_utterance (bool): + Optional. 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. + """ + + audio_encoding = proto.Field( + proto.ENUM, + number=1, + enum='AudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + enable_word_info = proto.Field( + proto.BOOL, + number=13, + ) + phrase_hints = proto.RepeatedField( + proto.STRING, + number=4, + ) + model = proto.Field( + proto.STRING, + number=7, + ) + model_variant = proto.Field( + proto.ENUM, + number=10, + enum='SpeechModelVariant', + ) + single_utterance = proto.Field( + proto.BOOL, + number=8, + ) + + +class VoiceSelectionParams(proto.Message): + r"""Description of which voice to use for speech synthesis. + Attributes: + name (str): + Optional. The name of the voice. If not set, the service + will choose a voice based on the other parameters such as + language_code and + [ssml_gender][google.cloud.dialogflow.cx.v3.VoiceSelectionParams.ssml_gender]. + + For the list of available voices, please refer to `Supported + voices and + languages `__. + ssml_gender (google.cloud.dialogflowcx_v3.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.cx.v3.VoiceSelectionParams.name]. + Note that this is only a preference, not requirement. If a + voice of the appropriate gender is not available, the + synthesizer substitutes 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.dialogflowcx_v3.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. + + Attributes: + audio_encoding (google.cloud.dialogflowcx_v3.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_config (google.cloud.dialogflowcx_v3.types.SynthesizeSpeechConfig): + Optional. 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', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py new file mode 100644 index 00000000..8aea5942 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py @@ -0,0 +1,425 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cx.v3', + manifest={ + 'EntityType', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'GetEntityTypeRequest', + 'CreateEntityTypeRequest', + 'UpdateEntityTypeRequest', + 'DeleteEntityTypeRequest', + }, +) + + +class EntityType(proto.Message): + r"""Entities are extracted from user input and represent parameters that + are meaningful to your application. For example, a date range, a + proper name such as a geographic location or landmark, and so on. + Entities represent actionable data for your application. + + When you define an entity, you can also include synonyms that all + map to that entity. For example, "soft drink", "soda", "pop", and so + on. + + There are three types of entities: + + - **System** - entities that are defined by the Dialogflow API for + common data types such as date, time, currency, and so on. A + system entity is represented by the ``EntityType`` type. + + - **Custom** - entities that are defined by you that represent + actionable data that is meaningful to your application. For + example, you could define a ``pizza.sauce`` entity for red or + white pizza sauce, a ``pizza.cheese`` entity for the different + types of cheese on a pizza, a ``pizza.topping`` entity for + different toppings, and so on. A custom entity is represented by + the ``EntityType`` type. + + - **User** - entities that are built for an individual user such as + favorites, preferences, playlists, and so on. A user entity is + represented by the + [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] + type. + + For more information about entity types, see the `Dialogflow + documentation `__. + + Attributes: + name (str): + The unique identifier of the entity type. Required for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. + Format: + ``projects//locations//agents//entityTypes/``. + display_name (str): + Required. The human-readable name of the + entity type, unique within the agent. + kind (google.cloud.dialogflowcx_v3.types.EntityType.Kind): + Required. Indicates the kind of entity type. + auto_expansion_mode (google.cloud.dialogflowcx_v3.types.EntityType.AutoExpansionMode): + Indicates whether the entity type can be + automatically expanded. + entities (Sequence[google.cloud.dialogflowcx_v3.types.EntityType.Entity]): + The collection of entity entries associated + with the entity type. + excluded_phrases (Sequence[google.cloud.dialogflowcx_v3.types.EntityType.ExcludedPhrase]): + Collection of exceptional words and phrases that shouldn't + be matched. For example, if you have a size entity type with + entry ``giant``\ (an adjective), you might consider adding + ``giants``\ (a noun) as an exclusion. If the kind of entity + type is ``KIND_MAP``, then the phrases specified by entities + and excluded phrases should be mutually exclusive. + enable_fuzzy_extraction (bool): + Enables fuzzy entity extraction during + classification. + redact (bool): + Indicates whether parameters of the entity + type should be redacted in log. If redaction is + enabled, page parameters and intent parameters + referring to the entity type will be replaced by + parameter name when logging. + """ + 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 canonical 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, + ) + + class ExcludedPhrase(proto.Message): + r"""An excluded entity phrase that should not be matched. + Attributes: + value (str): + Required. The word or phrase to be excluded. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + kind = proto.Field( + proto.ENUM, + number=3, + enum=Kind, + ) + auto_expansion_mode = proto.Field( + proto.ENUM, + number=4, + enum=AutoExpansionMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Entity, + ) + excluded_phrases = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=ExcludedPhrase, + ) + enable_fuzzy_extraction = proto.Field( + proto.BOOL, + number=7, + ) + redact = proto.Field( + proto.BOOL, + number=9, + ) + + +class ListEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. + + Attributes: + parent (str): + Required. The agent to list all entity types for. Format: + ``projects//locations//agents/``. + language_code (str): + The language to list entity types for. The following fields + are language dependent: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + 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. + 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, + ) + 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.cx.v3.EntityTypes.ListEntityTypes]. + + Attributes: + entity_types (Sequence[google.cloud.dialogflowcx_v3.types.EntityType]): + The list of 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.cx.v3.EntityTypes.GetEntityType]. + + Attributes: + name (str): + Required. The name of the entity type. Format: + ``projects//locations//agents//entityTypes/``. + language_code (str): + The language to retrieve the entity type for. The following + fields are language dependent: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + 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. + """ + + 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.cx.v3.EntityTypes.CreateEntityType]. + + Attributes: + parent (str): + Required. The agent to create a entity type for. Format: + ``projects//locations//agents/``. + entity_type (google.cloud.dialogflowcx_v3.types.EntityType): + Required. The entity type to create. + language_code (str): + The language of the following fields in ``entity_type``: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + 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, + ) + 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.cx.v3.EntityTypes.UpdateEntityType]. + + Attributes: + entity_type (google.cloud.dialogflowcx_v3.types.EntityType): + Required. The entity type to update. + language_code (str): + The language of the following fields in ``entity_type``: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + 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. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.cx.v3.EntityTypes.DeleteEntityType]. + + Attributes: + name (str): + Required. The name of the entity type to delete. Format: + ``projects//locations//agents//entityTypes/``. + force (bool): + This field has no effect for entity type not being used. For + entity types that are used by intents or pages: + + - If ``force`` is set to false, an error will be returned + with message indicating the referencing resources. + - If ``force`` is set to true, Dialogflow will remove the + entity type, as well as any references to the entity type + (i.e. Page + [parameter][google.cloud.dialogflow.cx.v3.Form.Parameter] + of the entity type will be changed to '@sys.any' and + intent + [parameter][google.cloud.dialogflow.cx.v3.Intent.Parameter] + of the entity type will be removed). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.py new file mode 100644 index 00000000..9736600a --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.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 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.cx.v3', + manifest={ + 'Environment', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'GetEnvironmentRequest', + 'CreateEnvironmentRequest', + 'UpdateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'LookupEnvironmentHistoryRequest', + 'LookupEnvironmentHistoryResponse', + }, +) + + +class Environment(proto.Message): + r"""Represents an environment for an agent. 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. + + Attributes: + name (str): + The name of the environment. Format: + ``projects//locations//agents//environments/``. + display_name (str): + Required. The human-readable name of the + environment (unique in an agent). Limit of 64 + characters. + description (str): + The human-readable description of the + environment. The maximum length is 500 + characters. If exceeded, the request is + rejected. + version_configs (Sequence[google.cloud.dialogflowcx_v3.types.Environment.VersionConfig]): + Required. A list of configurations for flow versions. You + should include version configs for all flows that are + reachable from [``Start Flow``][Agent.start_flow] in the + agent. Otherwise, an error will be returned. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time of this environment. + """ + + class VersionConfig(proto.Message): + r"""Configuration for the version. + Attributes: + version (str): + Required. Format: projects//locations//agents//flows//versions/. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + version_configs = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=VersionConfig, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class ListEnvironmentsRequest(proto.Message): + r"""The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. + + Attributes: + parent (str): + Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] + to list all environments for. Format: + ``projects//locations//agents/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 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 ListEnvironmentsResponse(proto.Message): + r"""The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. + + Attributes: + environments (Sequence[google.cloud.dialogflowcx_v3.types.Environment]): + The list of environments. There will be a maximum number of + items returned based on the page_size field in the request. + The list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + 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.cx.v3.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] + to create an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents/``. + environment (google.cloud.dialogflowcx_v3.types.Environment): + Required. The environment to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.MESSAGE, + number=2, + message='Environment', + ) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflowcx_v3.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + environment = proto.Field( + proto.MESSAGE, + number=1, + message='Environment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] to + delete. Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class LookupEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + + Attributes: + name (str): + Required. Resource name of the environment to look up the + history for. Format: + ``projects//locations//agents//environments/``. + 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. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class LookupEnvironmentHistoryResponse(proto.Message): + r"""The response message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. + + Attributes: + environments (Sequence[google.cloud.dialogflowcx_v3.types.Environment]): + Represents a list of snapshots for an environment. Time of + the snapshots is stored in + [``update_time``][google.cloud.dialogflow.cx.v3.Environment.update_time]. + 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, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py new file mode 100644 index 00000000..5d1bfd1e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py @@ -0,0 +1,568 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'Experiment', + 'VersionVariants', + 'VariantsHistory', + 'ListExperimentsRequest', + 'ListExperimentsResponse', + 'GetExperimentRequest', + 'CreateExperimentRequest', + 'UpdateExperimentRequest', + 'DeleteExperimentRequest', + 'StartExperimentRequest', + 'StopExperimentRequest', + }, +) + + +class Experiment(proto.Message): + r"""Represents an experiment in an environment. + Attributes: + name (str): + The name of the experiment. + Format: projects//locations//agents//environments//experiments/.. + display_name (str): + Required. The human-readable name of the + experiment (unique in an environment). Limit of + 64 characters. + description (str): + The human-readable description of the + experiment. + state (google.cloud.dialogflowcx_v3.types.Experiment.State): + The current state of the experiment. + Transition triggered by + Expriments.StartExperiment: PENDING->RUNNING. + Transition triggered by + Expriments.CancelExperiment: PENDING->CANCELLED + or RUNNING->CANCELLED. + definition (google.cloud.dialogflowcx_v3.types.Experiment.Definition): + The definition of the experiment. + result (google.cloud.dialogflowcx_v3.types.Experiment.Result): + Inference result of the experiment. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Creation time of this experiment. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of this experiment. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of this experiment. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Last update time of this experiment. + experiment_length (google.protobuf.duration_pb2.Duration): + Maximum number of days to run the + experiment/rollout. If auto-rollout is not + enabled, default value and maximum will be 30 + days. If auto-rollout is enabled, default value + and maximum will be 6 days. + variants_history (Sequence[google.cloud.dialogflowcx_v3.types.VariantsHistory]): + The history of updates to the experiment + variants. + """ + class State(proto.Enum): + r"""The state of the experiment.""" + STATE_UNSPECIFIED = 0 + DRAFT = 1 + RUNNING = 2 + DONE = 3 + + class Definition(proto.Message): + r"""Definition of the experiment. + Attributes: + condition (str): + The condition defines which subset of sessions are selected + for this experiment. If not specified, all sessions are + eligible. E.g. "query_input.language_code=en" See the + `conditions + reference `__. + version_variants (google.cloud.dialogflowcx_v3.types.VersionVariants): + The flow versions as the variants of this + experiment. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + version_variants = proto.Field( + proto.MESSAGE, + number=2, + oneof='variants', + message='VersionVariants', + ) + + class Result(proto.Message): + r"""The inference result which includes an objective metric to + optimize and the confidence interval. + + Attributes: + version_metrics (Sequence[google.cloud.dialogflowcx_v3.types.Experiment.Result.VersionMetrics]): + Version variants and metrics. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + The last time the experiment's stats data was + updated. Will have default value if stats have + never been computed for this experiment. + """ + class MetricType(proto.Enum): + r"""Types of ratio-based metric for Dialogflow experiment.""" + METRIC_UNSPECIFIED = 0 + CONTAINED_SESSION_NO_CALLBACK_RATE = 1 + LIVE_AGENT_HANDOFF_RATE = 2 + CALLBACK_SESSION_RATE = 3 + ABANDONED_SESSION_RATE = 4 + SESSION_END_RATE = 5 + + class CountType(proto.Enum): + r"""Types of count-based metric for Dialogflow experiment.""" + COUNT_TYPE_UNSPECIFIED = 0 + TOTAL_NO_MATCH_COUNT = 1 + TOTAL_TURN_COUNT = 2 + AVERAGE_TURN_COUNT = 3 + + class ConfidenceInterval(proto.Message): + r"""A confidence interval is a range of possible values for the + experiment objective you are trying to measure. + + Attributes: + confidence_level (float): + The confidence level used to construct the + interval, i.e. there is X% chance that the true + value is within this interval. + ratio (float): + The percent change between an experiment + metric's value and the value for its control. + lower_bound (float): + Lower bound of the interval. + upper_bound (float): + Upper bound of the interval. + """ + + confidence_level = proto.Field( + proto.DOUBLE, + number=1, + ) + ratio = proto.Field( + proto.DOUBLE, + number=2, + ) + lower_bound = proto.Field( + proto.DOUBLE, + number=3, + ) + upper_bound = proto.Field( + proto.DOUBLE, + number=4, + ) + + class Metric(proto.Message): + r"""Metric and corresponding confidence intervals. + Attributes: + type_ (google.cloud.dialogflowcx_v3.types.Experiment.Result.MetricType): + Ratio-based metric type. Only one of type or count_type is + specified in each Metric. + count_type (google.cloud.dialogflowcx_v3.types.Experiment.Result.CountType): + Count-based metric type. Only one of type or count_type is + specified in each Metric. + ratio (float): + Ratio value of a metric. + count (float): + Count value of a metric. + confidence_interval (google.cloud.dialogflowcx_v3.types.Experiment.Result.ConfidenceInterval): + The probability that the treatment is better + than all other treatments in the experiment + """ + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Experiment.Result.MetricType', + ) + count_type = proto.Field( + proto.ENUM, + number=5, + enum='Experiment.Result.CountType', + ) + ratio = proto.Field( + proto.DOUBLE, + number=2, + oneof='value', + ) + count = proto.Field( + proto.DOUBLE, + number=4, + oneof='value', + ) + confidence_interval = proto.Field( + proto.MESSAGE, + number=3, + message='Experiment.Result.ConfidenceInterval', + ) + + class VersionMetrics(proto.Message): + r"""Version variant and associated metrics. + Attributes: + version (str): + The name of the flow + [Version][google.cloud.dialogflow.cx.v3.Version]. Format: + ``projects//locations//agents//flows//versions/``. + metrics (Sequence[google.cloud.dialogflowcx_v3.types.Experiment.Result.Metric]): + The metrics and corresponding confidence + intervals in the inference result. + session_count (int): + Number of sessions that were allocated to + this version. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + metrics = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Experiment.Result.Metric', + ) + session_count = proto.Field( + proto.INT32, + number=3, + ) + + version_metrics = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Experiment.Result.VersionMetrics', + ) + last_update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + definition = proto.Field( + proto.MESSAGE, + number=5, + message=Definition, + ) + result = proto.Field( + proto.MESSAGE, + number=6, + message=Result, + ) + create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + start_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + last_update_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + experiment_length = proto.Field( + proto.MESSAGE, + number=11, + message=duration_pb2.Duration, + ) + variants_history = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='VariantsHistory', + ) + + +class VersionVariants(proto.Message): + r"""A list of flow version variants. + Attributes: + variants (Sequence[google.cloud.dialogflowcx_v3.types.VersionVariants.Variant]): + A list of flow version variants. + """ + + class Variant(proto.Message): + r"""A single flow version with specified traffic allocation. + Attributes: + version (str): + The name of the flow version. Format: + ``projects//locations//agents//flows//versions/``. + traffic_allocation (float): + Percentage of the traffic which should be + routed to this version of flow. Traffic + allocation for a single flow must sum up to 1.0. + is_control_group (bool): + Whether the variant is for the control group. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + traffic_allocation = proto.Field( + proto.FLOAT, + number=2, + ) + is_control_group = proto.Field( + proto.BOOL, + number=3, + ) + + variants = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Variant, + ) + + +class VariantsHistory(proto.Message): + r"""The history of variants update. + Attributes: + version_variants (google.cloud.dialogflowcx_v3.types.VersionVariants): + The flow versions as the variants. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Update time of the variants. + """ + + version_variants = proto.Field( + proto.MESSAGE, + number=1, + oneof='variants', + message='VersionVariants', + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ListExperimentsRequest(proto.Message): + r"""The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + Attributes: + parent (str): + Required. The + [Environment][google.cloud.dialogflow.cx.v3.Environment] to + list all environments for. Format: + ``projects//locations//agents//environments/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 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 ListExperimentsResponse(proto.Message): + r"""The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. + + Attributes: + experiments (Sequence[google.cloud.dialogflowcx_v3.types.Experiment]): + The list of experiments. There will be a maximum number of + items returned based on the page_size field in the request. + The list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + 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 + + experiments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Experiment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetExperimentRequest(proto.Message): + r"""The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateExperimentRequest(proto.Message): + r"""The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. + + Attributes: + parent (str): + Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] + to create an + [Environment][google.cloud.dialogflow.cx.v3.Environment] + for. Format: + ``projects//locations//agents//environments/``. + experiment (google.cloud.dialogflowcx_v3.types.Experiment): + Required. The experiment to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + experiment = proto.Field( + proto.MESSAGE, + number=2, + message='Experiment', + ) + + +class UpdateExperimentRequest(proto.Message): + r"""The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. + + Attributes: + experiment (google.cloud.dialogflowcx_v3.types.Experiment): + Required. The experiment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + experiment = proto.Field( + proto.MESSAGE, + number=1, + message='Experiment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteExperimentRequest(proto.Message): + r"""The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3.Environment] to + delete. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class StartExperimentRequest(proto.Message): + r"""The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. + + Attributes: + name (str): + Required. Resource name of the experiment to start. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class StopExperimentRequest(proto.Message): + r"""The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. + + Attributes: + name (str): + Required. Resource name of the experiment to stop. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py new file mode 100644 index 00000000..766f9cff --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py @@ -0,0 +1,640 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import validation_message +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'NluSettings', + 'Flow', + 'CreateFlowRequest', + 'DeleteFlowRequest', + 'ListFlowsRequest', + 'ListFlowsResponse', + 'GetFlowRequest', + 'UpdateFlowRequest', + 'TrainFlowRequest', + 'ValidateFlowRequest', + 'GetFlowValidationResultRequest', + 'FlowValidationResult', + 'ImportFlowRequest', + 'ImportFlowResponse', + 'ExportFlowRequest', + 'ExportFlowResponse', + }, +) + + +class NluSettings(proto.Message): + r"""Settings related to NLU. + Attributes: + model_type (google.cloud.dialogflowcx_v3.types.NluSettings.ModelType): + Indicates the type of NLU model. + classification_threshold (float): + 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 no-match event 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. + model_training_mode (google.cloud.dialogflowcx_v3.types.NluSettings.ModelTrainingMode): + Indicates NLU model training mode. + """ + class ModelType(proto.Enum): + r"""NLU model type.""" + MODEL_TYPE_UNSPECIFIED = 0 + MODEL_TYPE_STANDARD = 1 + MODEL_TYPE_ADVANCED = 3 + + class ModelTrainingMode(proto.Enum): + r"""NLU model training mode.""" + MODEL_TRAINING_MODE_UNSPECIFIED = 0 + MODEL_TRAINING_MODE_AUTOMATIC = 1 + MODEL_TRAINING_MODE_MANUAL = 2 + + model_type = proto.Field( + proto.ENUM, + number=1, + enum=ModelType, + ) + classification_threshold = proto.Field( + proto.FLOAT, + number=3, + ) + model_training_mode = proto.Field( + proto.ENUM, + number=4, + enum=ModelTrainingMode, + ) + + +class Flow(proto.Message): + r"""Flows represents the conversation flows when you build your + chatbot agent. + A flow consists of many pages connected by the transition + routes. Conversations always start with the built-in Start Flow + (with an all-0 ID). Transition routes can direct the + conversation session from the current flow (parent flow) to + another flow (sub flow). When the sub flow is finished, + Dialogflow will bring the session back to the parent flow, where + the sub flow is started. + + Usually, when a transition route is followed by a matched + intent, the intent will be "consumed". This means the intent + won't activate more transition routes. However, when the + followed transition route moves the conversation session into a + different flow, the matched intent can be carried over and to be + consumed in the target flow. + + Attributes: + name (str): + The unique identifier of the flow. Format: + ``projects//locations//agents//flows/``. + display_name (str): + Required. The human-readable name of the + flow. + description (str): + The description of the flow. The maximum + length is 500 characters. If exceeded, the + request is rejected. + transition_routes (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRoute]): + A flow's transition routes serve two purposes: + + - They are responsible for matching the user's first + utterances in the flow. + - They are inherited by every page's [transition + routes][Page.transition_routes] and can support use cases + such as the user saying "help" or "can I talk to a + human?", which can be handled in a common way regardless + of the current page. Transition routes defined in the + page have higher priority than those defined in the flow. + + TransitionRoutes are evalauted in the following order: + + - TransitionRoutes with intent specified.. + - TransitionRoutes with only condition specified. + + TransitionRoutes with intent specified are inherited by + pages in the flow. + event_handlers (Sequence[google.cloud.dialogflowcx_v3.types.EventHandler]): + A flow's event handlers serve two purposes: + + - They are responsible for handling events (e.g. no match, + webhook errors) in the flow. + - They are inherited by every page's [event + handlers][Page.event_handlers], which can be used to + handle common events regardless of the current page. + Event handlers defined in the page have higher priority + than those defined in the flow. + + Unlike + [transition_routes][google.cloud.dialogflow.cx.v3.Flow.transition_routes], + these handlers are evaluated on a first-match basis. The + first one that matches the event get executed, with the rest + being ignored. + transition_route_groups (Sequence[str]): + A flow's transition route group serve two purposes: + + - They are responsible for matching the user's first + utterances in the flow. + - They are inherited by every page's [transition route + groups][Page.transition_route_groups]. Transition route + groups defined in the page have higher priority than + those defined in the flow. + + Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. + nlu_settings (google.cloud.dialogflowcx_v3.types.NluSettings): + NLU related settings of the flow. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + transition_routes = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=page.TransitionRoute, + ) + event_handlers = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=page.EventHandler, + ) + transition_route_groups = proto.RepeatedField( + proto.STRING, + number=15, + ) + nlu_settings = proto.Field( + proto.MESSAGE, + number=11, + message='NluSettings', + ) + + +class CreateFlowRequest(proto.Message): + r"""The request message for + [Flows.CreateFlow][google.cloud.dialogflow.cx.v3.Flows.CreateFlow]. + + Attributes: + parent (str): + Required. The agent to create a flow for. Format: + ``projects//locations//agents/``. + flow (google.cloud.dialogflowcx_v3.types.Flow): + Required. The flow to create. + language_code (str): + The language of the following fields in ``flow``: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + flow = proto.Field( + proto.MESSAGE, + number=2, + message='Flow', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteFlowRequest(proto.Message): + r"""The request message for + [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3.Flows.DeleteFlow]. + + Attributes: + name (str): + Required. The name of the flow to delete. Format: + ``projects//locations//agents//flows/``. + force (bool): + This field has no effect for flows with no incoming + transitions. For flows with incoming transitions: + + - If ``force`` is set to false, an error will be returned + with message indicating the incoming transitions. + - If ``force`` is set to true, Dialogflow will remove the + flow, as well as any transitions to the flow (i.e. + [Target flow][EventHandler.target_flow] in event handlers + or [Target flow][TransitionRoute.target_flow] in + transition routes that point to this flow will be + cleared). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class ListFlowsRequest(proto.Message): + r"""The request message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + + Attributes: + parent (str): + Required. The agent containing the flows. Format: + ``projects//locations//agents/``. + 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. + language_code (str): + The language to list flows for. The following fields are + language dependent: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class ListFlowsResponse(proto.Message): + r"""The response message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. + + Attributes: + flows (Sequence[google.cloud.dialogflowcx_v3.types.Flow]): + The list of flows. 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 + + flows = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Flow', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFlowRequest(proto.Message): + r"""The response message for + [Flows.GetFlow][google.cloud.dialogflow.cx.v3.Flows.GetFlow]. + + Attributes: + name (str): + Required. The name of the flow to get. Format: + ``projects//locations//agents//flows/``. + language_code (str): + The language to retrieve the flow for. The following fields + are language dependent: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateFlowRequest(proto.Message): + r"""The request message for + [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3.Flows.UpdateFlow]. + + Attributes: + flow (google.cloud.dialogflowcx_v3.types.Flow): + Required. The flow to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields get updated. If + ``update_mask`` is not specified, an error will be returned. + language_code (str): + The language of the following fields in ``flow``: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + flow = proto.Field( + proto.MESSAGE, + number=1, + message='Flow', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class TrainFlowRequest(proto.Message): + r"""The request message for + [Flows.TrainFlow][google.cloud.dialogflow.cx.v3.Flows.TrainFlow]. + + Attributes: + name (str): + Required. The flow to train. Format: + ``projects//locations//agents//flows/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ValidateFlowRequest(proto.Message): + r"""The request message for + [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3.Flows.ValidateFlow]. + + Attributes: + name (str): + Required. The flow to validate. Format: + ``projects//locations//agents//flows/``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFlowValidationResultRequest(proto.Message): + r"""The request message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + Attributes: + name (str): + Required. The flow name. Format: + ``projects//locations//agents//flows//validationResult``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class FlowValidationResult(proto.Message): + r"""The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. + + Attributes: + name (str): + The unique identifier of the flow validation result. Format: + ``projects//locations//agents//flows//validationResult``. + validation_messages (Sequence[google.cloud.dialogflowcx_v3.types.ValidationMessage]): + Contains all validation messages. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Last time the flow was validated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + validation_messages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=validation_message.ValidationMessage, + ) + update_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class ImportFlowRequest(proto.Message): + r"""The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + Attributes: + parent (str): + Required. The agent to import the flow into. Format: + ``projects//locations//agents/``. + flow_uri (str): + The `Google Cloud + Storage `__ URI to + import flow from. The format of this URI must be + ``gs:///``. + flow_content (bytes): + Uncompressed raw byte content for flow. + import_option (google.cloud.dialogflowcx_v3.types.ImportFlowRequest.ImportOption): + Flow import mode. If not specified, ``KEEP`` is assumed. + """ + class ImportOption(proto.Enum): + r"""Import option.""" + IMPORT_OPTION_UNSPECIFIED = 0 + KEEP = 1 + FALLBACK = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + flow_uri = proto.Field( + proto.STRING, + number=2, + oneof='flow', + ) + flow_content = proto.Field( + proto.BYTES, + number=3, + oneof='flow', + ) + import_option = proto.Field( + proto.ENUM, + number=4, + enum=ImportOption, + ) + + +class ImportFlowResponse(proto.Message): + r"""The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + Attributes: + flow (str): + The unique identifier of the new flow. Format: + ``projects//locations//agents//flows/``. + """ + + flow = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportFlowRequest(proto.Message): + r"""The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + Attributes: + name (str): + Required. The name of the flow to export. Format: + ``projects//locations//agents//flows/``. + flow_uri (str): + Optional. The `Google Cloud + Storage `__ URI to + export the flow to. The format of this URI must be + ``gs:///``. If left unspecified, + the serialized flow is returned inline. + include_referenced_flows (bool): + Optional. Whether to export flows referenced + by the specified flow. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + flow_uri = proto.Field( + proto.STRING, + number=2, + ) + include_referenced_flows = proto.Field( + proto.BOOL, + number=4, + ) + + +class ExportFlowResponse(proto.Message): + r"""The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + Attributes: + flow_uri (str): + The URI to a file containing the exported flow. This field + is populated only if ``flow_uri`` is specified in + [ExportFlowRequest][google.cloud.dialogflow.cx.v3.ExportFlowRequest]. + flow_content (bytes): + Uncompressed raw byte content for flow. + """ + + flow_uri = proto.Field( + proto.STRING, + number=1, + oneof='flow', + ) + flow_content = proto.Field( + proto.BYTES, + number=2, + oneof='flow', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py new file mode 100644 index 00000000..93f3b79c --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import response_message +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'Fulfillment', + }, +) + + +class Fulfillment(proto.Message): + r"""A fulfillment can do one or more of the following actions at the + same time: + + - Generate rich message responses. + - Set parameter values. + - Call the webhook. + + Fulfillments can be called at various stages in the + [Page][google.cloud.dialogflow.cx.v3.Page] or + [Form][google.cloud.dialogflow.cx.v3.Form] lifecycle. For example, + when a + [DetectIntentRequest][google.cloud.dialogflow.cx.v3.DetectIntentRequest] + drives a session to enter a new page, the page's entry fulfillment + can add a static response to the + [QueryResult][google.cloud.dialogflow.cx.v3.QueryResult] in the + returning + [DetectIntentResponse][google.cloud.dialogflow.cx.v3.DetectIntentResponse], + call the webhook (for example, to load user data from a database), + or both. + + Attributes: + messages (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage]): + The list of rich message responses to present + to the user. + webhook (str): + The webhook to call. Format: + ``projects//locations//agents//webhooks/``. + tag (str): + The tag used by the webhook to identify which fulfillment is + being called. This field is required if ``webhook`` is + specified. + set_parameter_actions (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.SetParameterAction]): + Set parameter values before executing the + webhook. + conditional_cases (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases]): + Conditional cases for this fulfillment. + """ + + class SetParameterAction(proto.Message): + r"""Setting a parameter value. + Attributes: + parameter (str): + Display name of the parameter. + value (google.protobuf.struct_pb2.Value): + The new value of the parameter. A null value + clears the parameter. + """ + + parameter = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + class ConditionalCases(proto.Message): + r"""A list of cascading if-else conditions. Cases are mutually + exclusive. The first one with a matching condition is selected, + all the rest ignored. + + Attributes: + cases (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases.Case]): + A list of cascading if-else conditions. + """ + + class Case(proto.Message): + r"""Each case has a Boolean condition. When it is evaluated to be + True, the corresponding messages will be selected and evaluated + recursively. + + Attributes: + condition (str): + The condition to activate and select this case. Empty means + the condition is always true. The condition is evaluated + against [form parameters][Form.parameters] or [session + parameters][SessionInfo.parameters]. + + See the `conditions + reference `__. + case_content (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases.Case.CaseContent]): + A list of case content. + """ + + class CaseContent(proto.Message): + r"""The list of messages or conditional cases to activate for + this case. + + Attributes: + message (google.cloud.dialogflowcx_v3.types.ResponseMessage): + Returned message. + additional_cases (google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases): + Additional cases to be evaluated. + """ + + message = proto.Field( + proto.MESSAGE, + number=1, + oneof='cases_or_message', + message=response_message.ResponseMessage, + ) + additional_cases = proto.Field( + proto.MESSAGE, + number=2, + oneof='cases_or_message', + message='Fulfillment.ConditionalCases', + ) + + condition = proto.Field( + proto.STRING, + number=1, + ) + case_content = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Fulfillment.ConditionalCases.Case.CaseContent', + ) + + cases = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Fulfillment.ConditionalCases.Case', + ) + + messages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=response_message.ResponseMessage, + ) + webhook = proto.Field( + proto.STRING, + number=2, + ) + tag = proto.Field( + proto.STRING, + number=3, + ) + set_parameter_actions = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=SetParameterAction, + ) + conditional_cases = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=ConditionalCases, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py new file mode 100644 index 00000000..b0b25b6a --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py @@ -0,0 +1,474 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cx.v3', + manifest={ + 'IntentView', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'GetIntentRequest', + 'CreateIntentRequest', + 'UpdateIntentRequest', + 'DeleteIntentRequest', + }, +) + + +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. + """ + INTENT_VIEW_UNSPECIFIED = 0 + INTENT_VIEW_PARTIAL = 1 + INTENT_VIEW_FULL = 2 + + +class Intent(proto.Message): + r"""An intent represents a user's intent to interact with a + conversational agent. + You can provide information for the Dialogflow API to use to + match user input to an intent by adding training phrases (i.e., + examples of user input) to your intent. + + Attributes: + name (str): + The unique identifier of the intent. Required for the + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent] + method. + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent] + populates the name automatically. Format: + ``projects//locations//agents//intents/``. + display_name (str): + Required. The human-readable name of the + intent, unique within the agent. + training_phrases (Sequence[google.cloud.dialogflowcx_v3.types.Intent.TrainingPhrase]): + The collection of training phrases the agent + is trained on to identify the intent. + parameters (Sequence[google.cloud.dialogflowcx_v3.types.Intent.Parameter]): + The collection of parameters associated with + the intent. + priority (int): + 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): + Indicates whether this is a fallback intent. + Currently only default fallback intent is + allowed in the agent, which is added upon agent + creation. + Adding training phrases to fallback intent is + useful in the case of requests that are + mistakenly matched, since training phrases + assigned to fallback intents act as negative + examples that triggers no-match event. + labels (Sequence[google.cloud.dialogflowcx_v3.types.Intent.LabelsEntry]): + The key/value metadata to label an intent. Labels can + contain lowercase letters, digits and the symbols '-' and + '_'. International characters are allowed, including letters + from unicase alphabets. Keys must start with a letter. Keys + and values can be no longer than 63 characters and no more + than 128 bytes. + + Prefix "sys." is reserved for Dialogflow defined labels. + Currently allowed Dialogflow defined labels include: + + - sys.head + - sys.contextual The above labels do not require value. + "sys.head" means the intent is a head intent. + "sys.contextual" means the intent is a contextual intent. + description (str): + Human readable description for better + understanding an intent like its scope, content, + result etc. Maximum character limit: 140 + characters. + """ + + class TrainingPhrase(proto.Message): + r"""Represents an example that the agent is trained on to + identify the intent. + + Attributes: + id (str): + Output only. The unique identifier of the + training phrase. + parts (Sequence[google.cloud.dialogflowcx_v3.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.cx.v3.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 ``parameter_id`` field is set. + repeat_count (int): + Indicates how many times this example was + added to the intent. + """ + + class Part(proto.Message): + r"""Represents a part of a training phrase. + Attributes: + text (str): + Required. The text for this part. + parameter_id (str): + The + [parameter][google.cloud.dialogflow.cx.v3.Intent.Parameter] + used to annotate this part of the training phrase. This + field is required for annotated parts of the training + phrase. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + parameter_id = proto.Field( + proto.STRING, + number=2, + ) + + id = proto.Field( + proto.STRING, + number=1, + ) + parts = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.TrainingPhrase.Part', + ) + repeat_count = proto.Field( + proto.INT32, + number=3, + ) + + class Parameter(proto.Message): + r"""Represents an intent parameter. + Attributes: + id (str): + Required. The unique identifier of the parameter. This field + is used by [training + phrases][google.cloud.dialogflow.cx.v3.Intent.TrainingPhrase] + to annotate their + [parts][google.cloud.dialogflow.cx.v3.Intent.TrainingPhrase.Part]. + entity_type (str): + Required. The entity type of the parameter. Format: + ``projects/-/locations/-/agents/-/entityTypes/`` + for system entity types (for example, + ``projects/-/locations/-/agents/-/entityTypes/sys.date``), + or + ``projects//locations//agents//entityTypes/`` + for developer entity types. + is_list (bool): + Indicates whether the parameter represents a + list of values. + redact (bool): + Indicates whether the parameter content should be redacted + in log. If redaction is enabled, the parameter content will + be replaced by parameter name during logging. Note: the + parameter content is subject to redaction if either + parameter level redaction or [entity type level + redaction][google.cloud.dialogflow.cx.v3.EntityType.redact] + is enabled. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + is_list = proto.Field( + proto.BOOL, + number=3, + ) + redact = proto.Field( + proto.BOOL, + number=4, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + training_phrases = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TrainingPhrase, + ) + parameters = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Parameter, + ) + priority = proto.Field( + proto.INT32, + number=5, + ) + is_fallback = proto.Field( + proto.BOOL, + number=6, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + description = proto.Field( + proto.STRING, + number=8, + ) + + +class ListIntentsRequest(proto.Message): + r"""The request message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. + + Attributes: + parent (str): + Required. The agent to list all intents for. Format: + ``projects//locations//agents/``. + language_code (str): + The language to list intents for. The following fields are + language dependent: + + - ``Intent.training_phrases.parts.text`` + + 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. + intent_view (google.cloud.dialogflowcx_v3.types.IntentView): + The resource view to apply to the returned + intent. + 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, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = proto.Field( + proto.ENUM, + number=5, + enum='IntentView', + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListIntentsResponse(proto.Message): + r"""The response message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. + + Attributes: + intents (Sequence[google.cloud.dialogflowcx_v3.types.Intent]): + The list of 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.cx.v3.Intents.GetIntent]. + + Attributes: + name (str): + Required. The name of the intent. Format: + ``projects//locations//agents//intents/``. + language_code (str): + The language to retrieve the intent for. The following + fields are language dependent: + + - ``Intent.training_phrases.parts.text`` + + 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. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateIntentRequest(proto.Message): + r"""The request message for + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent]. + + Attributes: + parent (str): + Required. The agent to create an intent for. Format: + ``projects//locations//agents/``. + intent (google.cloud.dialogflowcx_v3.types.Intent): + Required. The intent to create. + language_code (str): + The language of the following fields in ``intent``: + + - ``Intent.training_phrases.parts.text`` + + 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, + ) + intent = proto.Field( + proto.MESSAGE, + number=2, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateIntentRequest(proto.Message): + r"""The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent]. + + Attributes: + intent (google.cloud.dialogflowcx_v3.types.Intent): + Required. The intent to update. + language_code (str): + The language of the following fields in ``intent``: + + - ``Intent.training_phrases.parts.text`` + + 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. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + updated. + """ + + 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, + ) + + +class DeleteIntentRequest(proto.Message): + r"""The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3.Intents.DeleteIntent]. + + Attributes: + name (str): + Required. The name of the intent to delete. Format: + ``projects//locations//agents//intents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py new file mode 100644 index 00000000..ee4be110 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'Page', + 'Form', + 'EventHandler', + 'TransitionRoute', + 'ListPagesRequest', + 'ListPagesResponse', + 'GetPageRequest', + 'CreatePageRequest', + 'UpdatePageRequest', + 'DeletePageRequest', + }, +) + + +class Page(proto.Message): + r"""A Dialogflow CX conversation (session) can be described and + visualized as a state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your combined pages can + handle a complete conversation on the topics the flow is designed + for. At any given moment, exactly one page is the current page, the + current page is considered active, and the flow associated with that + page is considered active. Every flow has a special start page. When + a flow initially becomes active, the start page page becomes the + current page. For each conversational turn, the current page will + either stay the same or transition to another page. + + You configure each page to collect information from the end-user + that is relevant for the conversational state represented by the + page. + + For more information, see the `Page + guide `__. + + Attributes: + name (str): + The unique identifier of the page. Required for the + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage] + method. + [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage] + populates the name automatically. Format: + ``projects//locations//agents//flows//pages/``. + display_name (str): + Required. The human-readable name of the + page, unique within the agent. + entry_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + The fulfillment to call when the session is + entering the page. + form (google.cloud.dialogflowcx_v3.types.Form): + The form associated with the page, used for + collecting parameters relevant to the page. + transition_route_groups (Sequence[str]): + Ordered list of + [``TransitionRouteGroups``][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + associated with the page. Transition route groups must be + unique within a page. + + - If multiple transition routes within a page scope refer + to the same intent, then the precedence order is: page's + transition route -> page's transition route group -> + flow's transition routes. + + - If multiple transition route groups within a page contain + the same intent, then the first group in the ordered list + takes precedence. + + Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. + transition_routes (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRoute]): + A list of transitions for the transition rules of this page. + They route the conversation to another page in the same + flow, or another flow. + + When we are in a certain page, the TransitionRoutes are + evalauted in the following order: + + - TransitionRoutes defined in the page with intent + specified. + - TransitionRoutes defined in the [transition route + groups][google.cloud.dialogflow.cx.v3.Page.transition_route_groups] + with intent specified. + - TransitionRoutes defined in flow with intent specified. + - TransitionRoutes defined in the [transition route + groups][google.cloud.dialogflow.cx.v3.Flow.transition_route_groups] + with intent specified. + - TransitionRoutes defined in the page with only condition + specified. + - TransitionRoutes defined in the [transition route + groups][google.cloud.dialogflow.cx.v3.Page.transition_route_groups] + with only condition specified. + event_handlers (Sequence[google.cloud.dialogflowcx_v3.types.EventHandler]): + Handlers associated with the page to handle + events such as webhook errors, no match or no + input. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + entry_fulfillment = proto.Field( + proto.MESSAGE, + number=7, + message=fulfillment.Fulfillment, + ) + form = proto.Field( + proto.MESSAGE, + number=4, + message='Form', + ) + transition_route_groups = proto.RepeatedField( + proto.STRING, + number=11, + ) + transition_routes = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='TransitionRoute', + ) + event_handlers = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='EventHandler', + ) + + +class Form(proto.Message): + r"""A form is a data model that groups related parameters that can be + collected from the user. The process in which the agent prompts the + user and collects parameter values from the user is called form + filling. A form can be added to a + [page][google.cloud.dialogflow.cx.v3.Page]. When form filling is + done, the filled parameters will be written to the + [session][google.cloud.dialogflow.cx.v3.SessionInfo.parameters]. + + Attributes: + parameters (Sequence[google.cloud.dialogflowcx_v3.types.Form.Parameter]): + Parameters to collect from the user. + """ + + class Parameter(proto.Message): + r"""Represents a form parameter. + Attributes: + display_name (str): + Required. The human-readable name of the + parameter, unique within the form. + required (bool): + Indicates whether the parameter is required. + Optional parameters will not trigger prompts; + however, they are filled if the user specifies + them. Required parameters must be filled before + form filling concludes. + entity_type (str): + Required. The entity type of the parameter. Format: + ``projects/-/locations/-/agents/-/entityTypes/`` + for system entity types (for example, + ``projects/-/locations/-/agents/-/entityTypes/sys.date``), + or + ``projects//locations//agents//entityTypes/`` + for developer entity types. + is_list (bool): + Indicates whether the parameter represents a + list of values. + fill_behavior (google.cloud.dialogflowcx_v3.types.Form.Parameter.FillBehavior): + Required. Defines fill behavior for the + parameter. + default_value (google.protobuf.struct_pb2.Value): + The default value of an optional parameter. + If the parameter is required, the default value + will be ignored. + redact (bool): + Indicates whether the parameter content should be redacted + in log. If redaction is enabled, the parameter content will + be replaced by parameter name during logging. Note: the + parameter content is subject to redaction if either + parameter level redaction or [entity type level + redaction][google.cloud.dialogflow.cx.v3.EntityType.redact] + is enabled. + """ + + class FillBehavior(proto.Message): + r"""Configuration for how the filling of a parameter should be + handled. + + Attributes: + initial_prompt_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + Required. The fulfillment to provide the + initial prompt that the agent can present to the + user in order to fill the parameter. + reprompt_event_handlers (Sequence[google.cloud.dialogflowcx_v3.types.EventHandler]): + The handlers for parameter-level events, used to provide + reprompt for the parameter or transition to a different + page/flow. The supported events are: + + - ``sys.no-match-``, where N can be from 1 to 6 + - ``sys.no-match-default`` + - ``sys.no-input-``, where N can be from 1 to 6 + - ``sys.no-input-default`` + - ``sys.invalid-parameter`` + + ``initial_prompt_fulfillment`` provides the first prompt for + the parameter. + + If the user's response does not fill the parameter, a + no-match/no-input event will be triggered, and the + fulfillment associated with the + ``sys.no-match-1``/``sys.no-input-1`` handler (if defined) + will be called to provide a prompt. The + ``sys.no-match-2``/``sys.no-input-2`` handler (if defined) + will respond to the next no-match/no-input event, and so on. + + A ``sys.no-match-default`` or ``sys.no-input-default`` + handler will be used to handle all following + no-match/no-input events after all numbered + no-match/no-input handlers for the parameter are consumed. + + A ``sys.invalid-parameter`` handler can be defined to handle + the case where the parameter values have been + ``invalidated`` by webhook. For example, if the user's + response fill the parameter, however the parameter was + invalidated by webhook, the fulfillment associated with the + ``sys.invalid-parameter`` handler (if defined) will be + called to provide a prompt. + + If the event handler for the corresponding event can't be + found on the parameter, ``initial_prompt_fulfillment`` will + be re-prompted. + """ + + initial_prompt_fulfillment = proto.Field( + proto.MESSAGE, + number=3, + message=fulfillment.Fulfillment, + ) + reprompt_event_handlers = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='EventHandler', + ) + + display_name = proto.Field( + proto.STRING, + number=1, + ) + required = proto.Field( + proto.BOOL, + number=2, + ) + entity_type = proto.Field( + proto.STRING, + number=3, + ) + is_list = proto.Field( + proto.BOOL, + number=4, + ) + fill_behavior = proto.Field( + proto.MESSAGE, + number=7, + message='Form.Parameter.FillBehavior', + ) + default_value = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Value, + ) + redact = proto.Field( + proto.BOOL, + number=11, + ) + + parameters = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Parameter, + ) + + +class EventHandler(proto.Message): + r"""An event handler specifies an + [event][google.cloud.dialogflow.cx.v3.EventHandler.event] that can + be handled during a session. When the specified event happens, the + following actions are taken in order: + + - If there is a + [``trigger_fulfillment``][google.cloud.dialogflow.cx.v3.EventHandler.trigger_fulfillment] + associated with the event, it will be called. + - If there is a + [``target_page``][google.cloud.dialogflow.cx.v3.EventHandler.target_page] + associated with the event, the session will transition into the + specified page. + - If there is a + [``target_flow``][google.cloud.dialogflow.cx.v3.EventHandler.target_flow] + associated with the event, the session will transition into the + specified flow. + + Attributes: + name (str): + Output only. The unique identifier of this + event handler. + event (str): + Required. The name of the event to handle. + trigger_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + The fulfillment to call when the event + occurs. Handling webhook errors with a + fulfillment enabled with webhook could cause + infinite loop. It is invalid to specify such + fulfillment for a handler handling webhooks. + target_page (str): + The target page to transition to. Format: + ``projects//locations//agents//flows//pages/``. + target_flow (str): + The target flow to transition to. Format: + ``projects//locations//agents//flows/``. + """ + + name = proto.Field( + proto.STRING, + number=6, + ) + event = proto.Field( + proto.STRING, + number=4, + ) + trigger_fulfillment = proto.Field( + proto.MESSAGE, + number=5, + message=fulfillment.Fulfillment, + ) + target_page = proto.Field( + proto.STRING, + number=2, + oneof='target', + ) + target_flow = proto.Field( + proto.STRING, + number=3, + oneof='target', + ) + + +class TransitionRoute(proto.Message): + r"""A transition route specifies a + [intent][google.cloud.dialogflow.cx.v3.Intent] that can be matched + and/or a data condition that can be evaluated during a session. When + a specified transition is matched, the following actions are taken + in order: + + - If there is a + [``trigger_fulfillment``][google.cloud.dialogflow.cx.v3.TransitionRoute.trigger_fulfillment] + associated with the transition, it will be called. + - If there is a + [``target_page``][google.cloud.dialogflow.cx.v3.TransitionRoute.target_page] + associated with the transition, the session will transition into + the specified page. + - If there is a + [``target_flow``][google.cloud.dialogflow.cx.v3.TransitionRoute.target_flow] + associated with the transition, the session will transition into + the specified flow. + + Attributes: + name (str): + Output only. The unique identifier of this + transition route. + intent (str): + The unique identifier of an + [Intent][google.cloud.dialogflow.cx.v3.Intent]. Format: + ``projects//locations//agents//intents/``. + Indicates that the transition can only happen when the given + intent is matched. At least one of ``intent`` or + ``condition`` must be specified. When both ``intent`` and + ``condition`` are specified, the transition can only happen + when both are fulfilled. + condition (str): + The condition to evaluate against [form + parameters][google.cloud.dialogflow.cx.v3.Form.parameters] + or [session + parameters][google.cloud.dialogflow.cx.v3.SessionInfo.parameters]. + + See the `conditions + reference `__. + At least one of ``intent`` or ``condition`` must be + specified. When both ``intent`` and ``condition`` are + specified, the transition can only happen when both are + fulfilled. + trigger_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): + The fulfillment to call when the condition is satisfied. At + least one of ``trigger_fulfillment`` and ``target`` must be + specified. When both are defined, ``trigger_fulfillment`` is + executed first. + target_page (str): + The target page to transition to. Format: + ``projects//locations//agents//flows//pages/``. + target_flow (str): + The target flow to transition to. Format: + ``projects//locations//agents//flows/``. + """ + + name = proto.Field( + proto.STRING, + number=6, + ) + intent = proto.Field( + proto.STRING, + number=1, + ) + condition = proto.Field( + proto.STRING, + number=2, + ) + trigger_fulfillment = proto.Field( + proto.MESSAGE, + number=3, + message=fulfillment.Fulfillment, + ) + target_page = proto.Field( + proto.STRING, + number=4, + oneof='target', + ) + target_flow = proto.Field( + proto.STRING, + number=5, + oneof='target', + ) + + +class ListPagesRequest(proto.Message): + r"""The request message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + + Attributes: + parent (str): + Required. The flow to list all pages for. Format: + ``projects//locations//agents//flows/``. + language_code (str): + The language to list pages for. The following fields are + language dependent: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + 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, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListPagesResponse(proto.Message): + r"""The response message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. + + Attributes: + pages (Sequence[google.cloud.dialogflowcx_v3.types.Page]): + The list of pages. 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 + + pages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Page', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetPageRequest(proto.Message): + r"""The request message for + [Pages.GetPage][google.cloud.dialogflow.cx.v3.Pages.GetPage]. + + Attributes: + name (str): + Required. The name of the page. Format: + ``projects//locations//agents//flows//pages/``. + language_code (str): + The language to retrieve the page for. The following fields + are language dependent: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreatePageRequest(proto.Message): + r"""The request message for + [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage]. + + Attributes: + parent (str): + Required. The flow to create a page for. Format: + ``projects//locations//agents//flows/``. + page (google.cloud.dialogflowcx_v3.types.Page): + Required. The page to create. + language_code (str): + The language of the following fields in ``page``: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page = proto.Field( + proto.MESSAGE, + number=2, + message='Page', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdatePageRequest(proto.Message): + r"""The request message for + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage]. + + Attributes: + page (google.cloud.dialogflowcx_v3.types.Page): + Required. The page to update. + language_code (str): + The language of the following fields in ``page``: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + updated. + """ + + page = proto.Field( + proto.MESSAGE, + number=1, + message='Page', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeletePageRequest(proto.Message): + r"""The request message for + [Pages.DeletePage][google.cloud.dialogflow.cx.v3.Pages.DeletePage]. + + Attributes: + name (str): + Required. The name of the page to delete. Format: + ``projects//locations//agents//Flows//pages/``. + force (bool): + This field has no effect for pages with no incoming + transitions. For pages with incoming transitions: + + - If ``force`` is set to false, an error will be returned + with message indicating the incoming transitions. + - If ``force`` is set to true, Dialogflow will remove the + page, as well as any transitions to the page (i.e. + [Target page][EventHandler.target_page] in event handlers + or [Target page][TransitionRoute.target_page] in + transition routes that point to this page will be + cleared). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py new file mode 100644 index 00000000..b6972d26 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py @@ -0,0 +1,340 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'ResponseMessage', + }, +) + + +class ResponseMessage(proto.Message): + r"""Represents a response message that can be returned by a + conversational agent. + + Response messages are also used for output audio synthesis. The + approach is as follows: + + - If at least one OutputAudioText response is present, then all + OutputAudioText responses are linearly concatenated, and the + result is used for output audio synthesis. + - If the OutputAudioText responses are a mixture of text and SSML, + then the concatenated result is treated as SSML; otherwise, the + result is treated as either text or SSML as appropriate. The + agent designer should ideally use either text or SSML + consistently throughout the bot design. + - Otherwise, all Text responses are linearly concatenated, and the + result is used for output audio synthesis. + + This approach allows for more sophisticated user experience + scenarios, where the text displayed to the user may differ from what + is heard. + + Attributes: + text (google.cloud.dialogflowcx_v3.types.ResponseMessage.Text): + Returns a text response. + payload (google.protobuf.struct_pb2.Struct): + Returns a response containing a custom, + platform-specific payload. + conversation_success (google.cloud.dialogflowcx_v3.types.ResponseMessage.ConversationSuccess): + Indicates that the conversation succeeded. + output_audio_text (google.cloud.dialogflowcx_v3.types.ResponseMessage.OutputAudioText): + A text or ssml response that is + preferentially used for TTS output audio + synthesis, as described in the comment on the + ResponseMessage message. + live_agent_handoff (google.cloud.dialogflowcx_v3.types.ResponseMessage.LiveAgentHandoff): + Hands off conversation to a human agent. + end_interaction (google.cloud.dialogflowcx_v3.types.ResponseMessage.EndInteraction): + Output only. A signal that indicates the interaction with + the Dialogflow agent has ended. This message is generated by + Dialogflow only when the conversation reaches + ``END_SESSION`` page. It is not supposed to be defined by + the user. + + It's guaranteed that there is at most one such message in + each response. + play_audio (google.cloud.dialogflowcx_v3.types.ResponseMessage.PlayAudio): + Signal that the client should play an audio clip hosted at a + client-specific URI. Dialogflow uses this to construct + [mixed_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.mixed_audio]. + However, Dialogflow itself does not try to read or process + the URI in any way. + mixed_audio (google.cloud.dialogflowcx_v3.types.ResponseMessage.MixedAudio): + Output only. An audio response message composed of both the + synthesized Dialogflow agent responses and responses defined + via + [play_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.play_audio]. + This message is generated by Dialogflow only and not + supposed to be defined by the user. + """ + + class Text(proto.Message): + r"""The text response message. + Attributes: + text (Sequence[str]): + Required. A collection of text responses. + allow_playback_interruption (bool): + Output only. Whether the playback of this + message can be interrupted by the end user's + speech and the client can then starts the next + Dialogflow request. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=2, + ) + + class LiveAgentHandoff(proto.Message): + r"""Indicates that the conversation should be handed off to a live + 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][google.cloud.dialogflow.cx.v3.Page.entry_fulfillment] + of a [Page][google.cloud.dialogflow.cx.v3.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 ConversationSuccess(proto.Message): + r"""Indicates that the conversation succeeded, i.e., the bot handled the + issue that the customer talked to it about. + + Dialogflow only uses this to determine which conversations should be + counted as successful and doesn't process the metadata in this + message in any way. Note that Dialogflow also considers + conversations that get to the conversation end page as successful + even if they don't return + [ConversationSuccess][google.cloud.dialogflow.cx.v3.ResponseMessage.ConversationSuccess]. + + You may set this, for example: + + - In the + [entry_fulfillment][google.cloud.dialogflow.cx.v3.Page.entry_fulfillment] + of a [Page][google.cloud.dialogflow.cx.v3.Page] if entering the + page indicates that the conversation succeeded. + - In a webhook response when you determine that you handled the + customer issue. + + Attributes: + metadata (google.protobuf.struct_pb2.Struct): + Custom metadata. Dialogflow doesn't impose + any structure on this. + """ + + metadata = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + class OutputAudioText(proto.Message): + r"""A text or ssml response that is preferentially used for TTS + output audio synthesis, as described in the comment on the + ResponseMessage message. + + Attributes: + text (str): + The raw text to be synthesized. + ssml (str): + The SSML text to be synthesized. For more information, see + `SSML `__. + allow_playback_interruption (bool): + Output only. Whether the playback of this + message can be interrupted by the end user's + speech and the client can then starts the next + Dialogflow request. + """ + + text = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + ssml = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=3, + ) + + class EndInteraction(proto.Message): + r"""Indicates that interaction with the Dialogflow agent has + ended. This message is generated by Dialogflow only and not + supposed to be defined by the user. + """ + + class PlayAudio(proto.Message): + r"""Specifies an audio clip to be played by the client as part of + the response. + + Attributes: + audio_uri (str): + Required. URI of the audio clip. Dialogflow + does not impose any validation on this value. It + is specific to the client that reads it. + allow_playback_interruption (bool): + Output only. Whether the playback of this + message can be interrupted by the end user's + speech and the client can then starts the next + Dialogflow request. + """ + + audio_uri = proto.Field( + proto.STRING, + number=1, + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=2, + ) + + class MixedAudio(proto.Message): + r"""Represents an audio message that is composed of both segments + synthesized from the Dialogflow agent prompts and ones hosted + externally at the specified URIs. The external URIs are specified + via + [play_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.play_audio]. + This message is generated by Dialogflow only and not supposed to be + defined by the user. + + Attributes: + segments (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage.MixedAudio.Segment]): + Segments this audio response is composed of. + """ + + class Segment(proto.Message): + r"""Represents one segment of audio. + Attributes: + audio (bytes): + Raw audio synthesized from the Dialogflow + agent's response using the output config + specified in the request. + uri (str): + Client-specific URI that points to an audio + clip accessible to the client. Dialogflow does + not impose any validation on it. + allow_playback_interruption (bool): + Output only. Whether the playback of this + segment can be interrupted by the end user's + speech and the client should then start the next + Dialogflow request. + """ + + audio = proto.Field( + proto.BYTES, + number=1, + oneof='content', + ) + uri = proto.Field( + proto.STRING, + number=2, + oneof='content', + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=3, + ) + + segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ResponseMessage.MixedAudio.Segment', + ) + + text = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message=Text, + ) + payload = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message=struct_pb2.Struct, + ) + conversation_success = proto.Field( + proto.MESSAGE, + number=9, + oneof='message', + message=ConversationSuccess, + ) + output_audio_text = proto.Field( + proto.MESSAGE, + number=8, + oneof='message', + message=OutputAudioText, + ) + live_agent_handoff = proto.Field( + proto.MESSAGE, + number=10, + oneof='message', + message=LiveAgentHandoff, + ) + end_interaction = proto.Field( + proto.MESSAGE, + number=11, + oneof='message', + message=EndInteraction, + ) + play_audio = proto.Field( + proto.MESSAGE, + number=12, + oneof='message', + message=PlayAudio, + ) + mixed_audio = proto.Field( + proto.MESSAGE, + number=13, + oneof='message', + message=MixedAudio, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py new file mode 100644 index 00000000..3ff3778e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cx.v3', + manifest={ + 'GetSecuritySettingsRequest', + 'UpdateSecuritySettingsRequest', + 'ListSecuritySettingsRequest', + 'ListSecuritySettingsResponse', + 'CreateSecuritySettingsRequest', + 'DeleteSecuritySettingsRequest', + 'SecuritySettings', + }, +) + + +class GetSecuritySettingsRequest(proto.Message): + r"""The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings]. + + Attributes: + name (str): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSecuritySettingsRequest(proto.Message): + r"""The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. + + Attributes: + security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): + Required. [SecuritySettings] object that contains values for + each of the fields 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. + """ + + security_settings = proto.Field( + proto.MESSAGE, + number=1, + message='SecuritySettings', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.ListSecuritySettings][]. + Attributes: + parent (str): + Required. The location to list all security settings for. + Format: ``projects//locations/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 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 ListSecuritySettingsResponse(proto.Message): + r"""The response message for [SecuritySettings.ListSecuritySettings][]. + Attributes: + security_settings (Sequence[google.cloud.dialogflowcx_v3.types.SecuritySettings]): + The list of security settings. + 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 + + security_settings = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SecuritySettings', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.CreateSecuritySettings][]. + Attributes: + parent (str): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + for. Format: + ``projects//locations/``. + security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): + Required. The security settings to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + security_settings = proto.Field( + proto.MESSAGE, + number=2, + message='SecuritySettings', + ) + + +class DeleteSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.DeleteSecuritySettings][]. + Attributes: + name (str): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class SecuritySettings(proto.Message): + r"""Represents the settings related to security issues, such as + data redaction and data retention. It may take hours for updates + on the settings to propagate to all the related components and + take effect. + + Attributes: + name (str): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + display_name (str): + Required. The human-readable name of the + security settings, unique within the location. + redaction_strategy (google.cloud.dialogflowcx_v3.types.SecuritySettings.RedactionStrategy): + Strategy that defines how we do redaction. + redaction_scope (google.cloud.dialogflowcx_v3.types.SecuritySettings.RedactionScope): + Defines the data for which Dialogflow applies + redaction. Dialogflow does not redact data that + it does not have access to – for example, Cloud + logging. + inspect_template (str): + DLP inspect template name. Use this template to define + inspect base settings. + + If empty, we use the default DLP inspect config. + + The template name will have one of the following formats: + ``projects/PROJECT_ID/inspectTemplates/TEMPLATE_ID`` OR + ``organizations/ORGANIZATION_ID/inspectTemplates/TEMPLATE_ID`` + retention_window_days (int): + Retains data in interaction logging for the + specified number of days. This does not apply to + Cloud logging, which is owned by the user - not + Dialogflow. + User must Set a value lower than Dialogflow's + default 30d TTL. Setting a value higher than + that has no effect. + A missing value or setting to 0 also means we + use Dialogflow's default TTL. + Note: Interaction logging is a limited access + feature. Talk to your Google representative to + check availability for you. + purge_data_types (Sequence[google.cloud.dialogflowcx_v3.types.SecuritySettings.PurgeDataType]): + List of types of data to remove when + retention settings triggers purge. + """ + class RedactionStrategy(proto.Enum): + r"""Defines how we redact data.""" + REDACTION_STRATEGY_UNSPECIFIED = 0 + REDACT_WITH_SERVICE = 1 + + class RedactionScope(proto.Enum): + r"""Defines what types of data to redact.""" + REDACTION_SCOPE_UNSPECIFIED = 0 + REDACT_DISK_STORAGE = 2 + + class PurgeDataType(proto.Enum): + r"""Type of data we purge after retention settings triggers + purge. + """ + PURGE_DATA_TYPE_UNSPECIFIED = 0 + DIALOGFLOW_HISTORY = 1 + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + redaction_strategy = proto.Field( + proto.ENUM, + number=3, + enum=RedactionStrategy, + ) + redaction_scope = proto.Field( + proto.ENUM, + number=4, + enum=RedactionScope, + ) + inspect_template = proto.Field( + proto.STRING, + number=9, + ) + retention_window_days = proto.Field( + proto.INT32, + number=6, + oneof='data_retention', + ) + purge_data_types = proto.RepeatedField( + proto.ENUM, + number=8, + enum=PurgeDataType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session.py new file mode 100644 index 00000000..c8f12205 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session.py @@ -0,0 +1,1167 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import audio_config +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import response_message +from google.cloud.dialogflowcx_v3.types import session_entity_type +from google.protobuf import duration_pb2 # 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.cx.v3', + manifest={ + 'DetectIntentRequest', + 'DetectIntentResponse', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'QueryParameters', + 'QueryInput', + 'QueryResult', + 'TextInput', + 'IntentInput', + 'AudioInput', + 'EventInput', + 'DtmfInput', + 'Match', + 'MatchIntentRequest', + 'MatchIntentResponse', + 'FulfillIntentRequest', + 'FulfillIntentResponse', + 'SentimentAnalysisResult', + }, +) + + +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//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. It's up to the API caller to choose an + appropriate ``Session ID``. It can be a random number or + some type of session identifiers (preferably hashed). The + length of the ``Session ID`` must not exceed 36 characters. + + For more information, see the `sessions + guide `__. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + query_params (google.cloud.dialogflowcx_v3.types.QueryParameters): + The parameters of this query. + query_input (google.cloud.dialogflowcx_v3.types.QueryInput): + Required. The input specification. + output_audio_config (google.cloud.dialogflowcx_v3.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate the output audio. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=4, + message=audio_config.OutputAudioConfig, + ) + + +class DetectIntentResponse(proto.Message): + r"""The message returned from the DetectIntent method. + Attributes: + response_id (str): + Output only. 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.dialogflowcx_v3.types.QueryResult): + The result of the conversational query. + 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.response_messages``][google.cloud.dialogflow.cx.v3.QueryResult.response_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.dialogflowcx_v3.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', + ) + output_audio = proto.Field( + proto.BYTES, + number=4, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=5, + message=audio_config.OutputAudioConfig, + ) + + +class StreamingDetectIntentRequest(proto.Message): + r"""The top-level message sent by the client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] + method. + + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it should also + contain + [output_audio_config][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.output_audio_config]. + + 2. If + [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio.config][google.cloud.dialogflow.cx.v3.AudioInput.config], + all subsequent messages must contain + [query_input.audio.audio][google.cloud.dialogflow.cx.v3.AudioInput.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.cx.v3.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): + The name of the session this query is sent to. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. It's up to the API caller to choose an + appropriate ``Session ID``. It can be a random number or + some type of session identifiers (preferably hashed). The + length of the ``Session ID`` must not exceed 36 characters. + Note: session must be set in the first request. + + For more information, see the `sessions + guide `__. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + query_params (google.cloud.dialogflowcx_v3.types.QueryParameters): + The parameters of this query. + query_input (google.cloud.dialogflowcx_v3.types.QueryInput): + Required. The input specification. + output_audio_config (google.cloud.dialogflowcx_v3.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate the output audio. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=4, + message=audio_config.OutputAudioConfig, + ) + + +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. If ``enable_partial_response`` is true, the following N messages + (currently 1 <= N <= 4) contain ``detect_intent_response``. The + first (N-1) ``detect_intent_response``\ s will have + ``response_type`` set to ``PARTIAL``. The last + ``detect_intent_response`` has ``response_type`` set to + ``FINAL``. If ``response_type`` is false, response stream only + contains the final ``detect_intent_response``. + + Attributes: + recognition_result (google.cloud.dialogflowcx_v3.types.StreamingRecognitionResult): + The result of speech recognition. + detect_intent_response (google.cloud.dialogflowcx_v3.types.DetectIntentResponse): + The response from detect intent. + """ + + recognition_result = proto.Field( + proto.MESSAGE, + number=1, + oneof='response', + message='StreamingRecognitionResult', + ) + detect_intent_response = proto.Field( + proto.MESSAGE, + number=2, + oneof='response', + message='DetectIntentResponse', + ) + + +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.dialogflowcx_v3.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.dialogflowcx_v3.types.SpeechWordInfo]): + Word-specific information for the words recognized by Speech + in + [transcript][google.cloud.dialogflow.cx.v3.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, + ) + stability = proto.Field( + proto.FLOAT, + number=6, + ) + speech_word_info = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=audio_config.SpeechWordInfo, + ) + speech_end_offset = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class QueryParameters(proto.Message): + r"""Represents the parameters of a conversational query. + Attributes: + time_zone (str): + The time zone of this conversational query from the `time + zone database `__, e.g., + America/New_York, Europe/Paris. If not provided, the time + zone specified in the agent is used. + geo_location (google.type.latlng_pb2.LatLng): + The geo location of this conversational + query. + session_entity_types (Sequence[google.cloud.dialogflowcx_v3.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 into the webhook + associated with the agent. Arbitrary JSON objects are + supported. Some integrations that query a Dialogflow agent + may provide additional information in the payload. In + particular, for the Dialogflow Phone Gateway integration, + this field has the form: + + :: + + { + "telephony": { + "caller_id": "+18558363987" + } + } + parameters (google.protobuf.struct_pb2.Struct): + Additional parameters to be put into [session + parameters][SessionInfo.parameters]. To remove a parameter + from the session, clients should explicitly set the + parameter value to null. + + You can reference the session parameters in the agent with + the following format: $session.params.parameter-id. + + 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 + current_page (str): + The unique identifier of the + [page][google.cloud.dialogflow.cx.v3.Page] to override the + [current page][QueryResult.current_page] in the session. + Format: + ``projects//locations//agents//pages/``. + + If ``current_page`` is specified, the previous state of the + session will be ignored by Dialogflow, including the + [previous page][QueryResult.current_page] and the [previous + session parameters][QueryResult.parameters]. In most cases, + [current_page][google.cloud.dialogflow.cx.v3.QueryParameters.current_page] + and + [parameters][google.cloud.dialogflow.cx.v3.QueryParameters.parameters] + should be configured together to direct a session to a + specific state. + disable_webhook (bool): + Whether to disable webhook calls for this + request. + analyze_query_text_sentiment (bool): + Configures whether sentiment analysis should + be performed. If not provided, sentiment + analysis is not performed. + webhook_headers (Sequence[google.cloud.dialogflowcx_v3.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, + ) + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=session_entity_type.SessionEntityType, + ) + payload = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + parameters = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) + current_page = proto.Field( + proto.STRING, + number=6, + ) + disable_webhook = proto.Field( + proto.BOOL, + number=7, + ) + analyze_query_text_sentiment = proto.Field( + proto.BOOL, + number=8, + ) + webhook_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + + +class QueryInput(proto.Message): + r"""Represents the query input. It can contain one of: + 1. A conversational query in the form of text. + + 2. An intent query that specifies which intent to trigger. + 3. Natural language speech audio to be processed. + + 4. An event to be triggered. + + Attributes: + text (google.cloud.dialogflowcx_v3.types.TextInput): + The natural language text to be processed. + intent (google.cloud.dialogflowcx_v3.types.IntentInput): + The intent to be triggered. + audio (google.cloud.dialogflowcx_v3.types.AudioInput): + The natural language speech audio to be + processed. + event (google.cloud.dialogflowcx_v3.types.EventInput): + The event to be triggered. + dtmf (google.cloud.dialogflowcx_v3.types.DtmfInput): + The DTMF event to be handled. + language_code (str): + Required. The language of the input. 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.MESSAGE, + number=2, + oneof='input', + message='TextInput', + ) + intent = proto.Field( + proto.MESSAGE, + number=3, + oneof='input', + message='IntentInput', + ) + audio = proto.Field( + proto.MESSAGE, + number=5, + oneof='input', + message='AudioInput', + ) + event = proto.Field( + proto.MESSAGE, + number=6, + oneof='input', + message='EventInput', + ) + dtmf = proto.Field( + proto.MESSAGE, + number=7, + oneof='input', + message='DtmfInput', + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class QueryResult(proto.Message): + r"""Represents the result of a conversational query. + Attributes: + text (str): + If [natural language + text][google.cloud.dialogflow.cx.v3.TextInput] was provided + as input, this field will contain a copy of the text. + trigger_intent (str): + If an [intent][google.cloud.dialogflow.cx.v3.IntentInput] + was provided as input, this field will contain a copy of the + intent identifier. Format: + ``projects//locations//agents//intents/``. + transcript (str): + If [natural language speech + audio][google.cloud.dialogflow.cx.v3.AudioInput] was + provided as input, this field will contain the transcript + for the audio. + trigger_event (str): + If an [event][google.cloud.dialogflow.cx.v3.EventInput] was + provided as input, this field will contain the name of the + event. + language_code (str): + The language that was triggered during intent detection. See + `Language + Support `__ + for a list of the currently supported language codes. + parameters (google.protobuf.struct_pb2.Struct): + The collected [session + parameters][google.cloud.dialogflow.cx.v3.SessionInfo.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 + response_messages (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage]): + The list of rich messages returned to the + client. Responses vary from simple text messages + to more sophisticated, structured payloads used + to drive complex logic. + webhook_statuses (Sequence[google.rpc.status_pb2.Status]): + The list of webhook call status in the order + of call sequence. + webhook_payloads (Sequence[google.protobuf.struct_pb2.Struct]): + The list of webhook payload in + [WebhookResponse.payload][google.cloud.dialogflow.cx.v3.WebhookResponse.payload], + in the order of call sequence. If some webhook call fails or + doesn't return any payload, an empty ``Struct`` would be + used instead. + current_page (google.cloud.dialogflowcx_v3.types.Page): + The current [Page][google.cloud.dialogflow.cx.v3.Page]. + Some, not all fields are filled in this message, including + but not limited to ``name`` and ``display_name``. + intent (google.cloud.dialogflowcx_v3.types.Intent): + The [Intent][google.cloud.dialogflow.cx.v3.Intent] that + matched the conversational query. Some, not all fields are + filled in this message, including but not limited to: + ``name`` and ``display_name``. This field is deprecated, + please use + [QueryResult.match][google.cloud.dialogflow.cx.v3.QueryResult.match] + instead. + 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. This field is deprecated, please use + [QueryResult.match][google.cloud.dialogflow.cx.v3.QueryResult.match] + instead. + match (google.cloud.dialogflowcx_v3.types.Match): + Intent match result, could be an intent or an + event. + diagnostic_info (google.protobuf.struct_pb2.Struct): + The free-form diagnostic info. For example, + this field could contain webhook call latency. + The string keys of the Struct's fields map can + change without notice. + sentiment_analysis_result (google.cloud.dialogflowcx_v3.types.SentimentAnalysisResult): + The sentiment analyss result, which depends on + [``analyze_query_text_sentiment``] + [google.cloud.dialogflow.cx.v3.QueryParameters.analyze_query_text_sentiment], + specified in the request. + """ + + text = proto.Field( + proto.STRING, + number=1, + oneof='query', + ) + trigger_intent = proto.Field( + proto.STRING, + number=11, + oneof='query', + ) + transcript = proto.Field( + proto.STRING, + number=12, + oneof='query', + ) + trigger_event = proto.Field( + proto.STRING, + number=14, + oneof='query', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + parameters = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + response_messages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=response_message.ResponseMessage, + ) + webhook_statuses = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=status_pb2.Status, + ) + webhook_payloads = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + current_page = proto.Field( + proto.MESSAGE, + number=7, + message=page.Page, + ) + intent = proto.Field( + proto.MESSAGE, + number=8, + message=gcdc_intent.Intent, + ) + intent_detection_confidence = proto.Field( + proto.FLOAT, + number=9, + ) + match = proto.Field( + proto.MESSAGE, + number=15, + message='Match', + ) + diagnostic_info = proto.Field( + proto.MESSAGE, + number=10, + message=struct_pb2.Struct, + ) + sentiment_analysis_result = proto.Field( + proto.MESSAGE, + number=17, + message='SentimentAnalysisResult', + ) + + +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. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + + +class IntentInput(proto.Message): + r"""Represents the intent to trigger programmatically rather than + as a result of natural language processing. + + Attributes: + intent (str): + Required. The unique identifier of the intent. Format: + ``projects//locations//agents//intents/``. + """ + + intent = proto.Field( + proto.STRING, + number=1, + ) + + +class AudioInput(proto.Message): + r"""Represents the natural speech audio to be processed. + Attributes: + config (google.cloud.dialogflowcx_v3.types.InputAudioConfig): + Required. Instructs the speech recognizer how + to process the speech audio. + audio (bytes): + The natural language speech audio to be processed. A single + request can contain up to 1 minute of speech audio data. The + [transcribed + text][google.cloud.dialogflow.cx.v3.QueryResult.transcript] + cannot contain more than 256 bytes. + + For non-streaming audio detect intent, both ``config`` and + ``audio`` must be provided. For streaming audio detect + intent, ``config`` must be provided in the first request and + ``audio`` must be provided in all following requests. + """ + + config = proto.Field( + proto.MESSAGE, + number=1, + message=audio_config.InputAudioConfig, + ) + audio = proto.Field( + proto.BYTES, + number=2, + ) + + +class EventInput(proto.Message): + r"""Represents the event to trigger. + Attributes: + event (str): + Name of the event. + """ + + event = proto.Field( + proto.STRING, + number=1, + ) + + +class DtmfInput(proto.Message): + r"""Represents the input for dtmf event. + Attributes: + digits (str): + The dtmf digits. + finish_digit (str): + The finish digit (if any). + """ + + digits = proto.Field( + proto.STRING, + number=1, + ) + finish_digit = proto.Field( + proto.STRING, + number=2, + ) + + +class Match(proto.Message): + r"""Represents one match result of [MatchIntent][]. + Attributes: + intent (google.cloud.dialogflowcx_v3.types.Intent): + The [Intent][google.cloud.dialogflow.cx.v3.Intent] that + matched the query. Some, not all fields are filled in this + message, including but not limited to: ``name`` and + ``display_name``. Only filled for + [``INTENT``][google.cloud.dialogflow.cx.v3.Match.MatchType] + match type. + event (str): + The event that matched the query. Only filled for + [``EVENT``][google.cloud.dialogflow.cx.v3.Match.MatchType] + match type. + parameters (google.protobuf.struct_pb2.Struct): + The collection of parameters extracted from + the query. + 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 + resolved_input (str): + Final text input which was matched during + MatchIntent. This value can be different from + original input sent in request because of + spelling correction or other processing. + match_type (google.cloud.dialogflowcx_v3.types.Match.MatchType): + Type of this [Match][google.cloud.dialogflow.cx.v3.Match]. + confidence (float): + The confidence of this match. Values range + from 0.0 (completely uncertain) to 1.0 + (completely certain). This value is for + informational purpose only and is only used to + help match the best intent within the + classification threshold. This value may change + for the same end-user expression at any time due + to a model retraining or change in + implementation. + """ + class MatchType(proto.Enum): + r"""Type of a Match.""" + MATCH_TYPE_UNSPECIFIED = 0 + INTENT = 1 + DIRECT_INTENT = 2 + PARAMETER_FILLING = 3 + NO_MATCH = 4 + NO_INPUT = 5 + EVENT = 6 + + intent = proto.Field( + proto.MESSAGE, + number=1, + message=gcdc_intent.Intent, + ) + event = proto.Field( + proto.STRING, + number=6, + ) + parameters = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + resolved_input = proto.Field( + proto.STRING, + number=3, + ) + match_type = proto.Field( + proto.ENUM, + number=4, + enum=MatchType, + ) + confidence = proto.Field( + proto.FLOAT, + number=5, + ) + + +class MatchIntentRequest(proto.Message): + r"""Request of [MatchIntent][]. + Attributes: + session (str): + Required. The name of the session this query is sent to. + Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. It's up to the API caller to choose an + appropriate ``Session ID``. It can be a random number or + some type of session identifiers (preferably hashed). The + length of the ``Session ID`` must not exceed 36 characters. + + For more information, see the `sessions + guide `__. + query_params (google.cloud.dialogflowcx_v3.types.QueryParameters): + The parameters of this query. + query_input (google.cloud.dialogflowcx_v3.types.QueryInput): + Required. The input specification. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + + +class MatchIntentResponse(proto.Message): + r"""Response of [MatchIntent][]. + Attributes: + text (str): + If [natural language + text][google.cloud.dialogflow.cx.v3.TextInput] was provided + as input, this field will contain a copy of the text. + trigger_intent (str): + If an [intent][google.cloud.dialogflow.cx.v3.IntentInput] + was provided as input, this field will contain a copy of the + intent identifier. Format: + ``projects//locations//agents//intents/``. + transcript (str): + If [natural language speech + audio][google.cloud.dialogflow.cx.v3.AudioInput] was + provided as input, this field will contain the transcript + for the audio. + trigger_event (str): + If an [event][google.cloud.dialogflow.cx.v3.EventInput] was + provided as input, this field will contain a copy of the + event name. + matches (Sequence[google.cloud.dialogflowcx_v3.types.Match]): + Match results, if more than one, ordered + descendingly by the confidence we have that the + particular intent matches the query. + current_page (google.cloud.dialogflowcx_v3.types.Page): + The current [Page][google.cloud.dialogflow.cx.v3.Page]. + Some, not all fields are filled in this message, including + but not limited to ``name`` and ``display_name``. + """ + + text = proto.Field( + proto.STRING, + number=1, + oneof='query', + ) + trigger_intent = proto.Field( + proto.STRING, + number=2, + oneof='query', + ) + transcript = proto.Field( + proto.STRING, + number=3, + oneof='query', + ) + trigger_event = proto.Field( + proto.STRING, + number=6, + oneof='query', + ) + matches = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Match', + ) + current_page = proto.Field( + proto.MESSAGE, + number=5, + message=page.Page, + ) + + +class FulfillIntentRequest(proto.Message): + r"""Request of [FulfillIntent][] + Attributes: + match_intent_request (google.cloud.dialogflowcx_v3.types.MatchIntentRequest): + Must be same as the corresponding MatchIntent + request, otherwise the behavior is undefined. + match (google.cloud.dialogflowcx_v3.types.Match): + The matched intent/event to fulfill. + output_audio_config (google.cloud.dialogflowcx_v3.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate output audio. + """ + + match_intent_request = proto.Field( + proto.MESSAGE, + number=1, + message='MatchIntentRequest', + ) + match = proto.Field( + proto.MESSAGE, + number=2, + message='Match', + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=3, + message=audio_config.OutputAudioConfig, + ) + + +class FulfillIntentResponse(proto.Message): + r"""Response of [FulfillIntent][] + Attributes: + response_id (str): + Output only. 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.dialogflowcx_v3.types.QueryResult): + The result of the conversational query. + 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.response_messages``][google.cloud.dialogflow.cx.v3.QueryResult.response_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.dialogflowcx_v3.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', + ) + output_audio = proto.Field( + proto.BYTES, + number=3, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=4, + message=audio_config.OutputAudioConfig, + ) + + +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. + + 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/v3/google/cloud/dialogflowcx_v3/types/session_entity_type.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session_entity_type.py new file mode 100644 index 00000000..251c7b38 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session_entity_type.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 proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import entity_type +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'SessionEntityType', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'GetSessionEntityTypeRequest', + 'CreateSessionEntityTypeRequest', + 'UpdateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + }, +) + + +class SessionEntityType(proto.Message): + r"""Session entity types are referred to as **User** entity types and + are entities that are built for an individual user such as + favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session level to + extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3.EntityType] at the user session + level (we refer to the entity types defined at the agent level as + "custom entity types"). + + Note: session entity types apply to all queries, regardless of the + language. + + For more information about entity types, see the `Dialogflow + documentation `__. + + Attributes: + name (str): + Required. The unique identifier of the session entity type. + Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + entity_override_mode (google.cloud.dialogflowcx_v3.types.SessionEntityType.EntityOverrideMode): + Required. Indicates whether the additional + data should override or supplement the custom + entity type definition. + entities (Sequence[google.cloud.dialogflowcx_v3.types.EntityType.Entity]): + Required. The collection of entities to + override or supplement the custom entity type. + """ + class EntityOverrideMode(proto.Enum): + r"""The types of modifications for the 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=3, + enum=EntityOverrideMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=entity_type.EntityType.Entity, + ) + + +class ListSessionEntityTypesRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. + + Attributes: + parent (str): + Required. The session to list all session entity types from. + Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + 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 ListSessionEntityTypesResponse(proto.Message): + r"""The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. + + Attributes: + session_entity_types (Sequence[google.cloud.dialogflowcx_v3.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.cx.v3.SessionEntityTypes.GetSessionEntityType]. + + Attributes: + name (str): + Required. The name of the session entity type. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSessionEntityTypeRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType]. + + Attributes: + parent (str): + Required. The session to create a session entity type for. + Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + session_entity_type (google.cloud.dialogflowcx_v3.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.cx.v3.SessionEntityTypes.UpdateSessionEntityType]. + + Attributes: + session_entity_type (google.cloud.dialogflowcx_v3.types.SessionEntityType): + Required. The session entity type to update. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.cx.v3.SessionEntityTypes.DeleteSessionEntityType]. + + Attributes: + name (str): + Required. The name of the session entity type to delete. + Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/test_case.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/test_case.py new file mode 100644 index 00000000..7649a249 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/test_case.py @@ -0,0 +1,1248 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import flow as gcdc_flow +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.cloud.dialogflowcx_v3.types import response_message +from google.cloud.dialogflowcx_v3.types import session +from google.cloud.dialogflowcx_v3.types import transition_route_group +from google.protobuf import field_mask_pb2 # 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.cx.v3', + manifest={ + 'TestResult', + 'TestCase', + 'TestCaseResult', + 'TestConfig', + 'ConversationTurn', + 'TestRunDifference', + 'TransitionCoverage', + 'TransitionRouteGroupCoverage', + 'IntentCoverage', + 'CalculateCoverageRequest', + 'CalculateCoverageResponse', + 'ListTestCasesRequest', + 'ListTestCasesResponse', + 'BatchDeleteTestCasesRequest', + 'CreateTestCaseRequest', + 'UpdateTestCaseRequest', + 'GetTestCaseRequest', + 'RunTestCaseRequest', + 'RunTestCaseResponse', + 'RunTestCaseMetadata', + 'BatchRunTestCasesRequest', + 'BatchRunTestCasesResponse', + 'BatchRunTestCasesMetadata', + 'TestError', + 'ImportTestCasesRequest', + 'ImportTestCasesResponse', + 'ImportTestCasesMetadata', + 'TestCaseError', + 'ExportTestCasesRequest', + 'ExportTestCasesResponse', + 'ExportTestCasesMetadata', + 'ListTestCaseResultsRequest', + 'ListTestCaseResultsResponse', + 'GetTestCaseResultRequest', + }, +) + + +class TestResult(proto.Enum): + r"""The test result for a test case and an agent environment.""" + TEST_RESULT_UNSPECIFIED = 0 + PASSED = 1 + FAILED = 2 + + +class TestCase(proto.Message): + r"""Represents a test case. + Attributes: + name (str): + The unique identifier of the test case. + [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase] + will populate the name automatically. Otherwise use format: + ``projects//locations//agents/ /testCases/``. + tags (Sequence[str]): + Tags are short descriptions that users may + apply to test cases for organizational and + filtering purposes. Each tag should start with + "#" and has a limit of 30 characters. + display_name (str): + Required. The human-readable name of the test + case, unique within the agent. Limit of 200 + characters. + notes (str): + Additional freeform notes about the test + case. Limit of 400 characters. + test_config (google.cloud.dialogflowcx_v3.types.TestConfig): + Config for the test case. + test_case_conversation_turns (Sequence[google.cloud.dialogflowcx_v3.types.ConversationTurn]): + The conversation turns uttered when the test + case was created, in chronological order. These + include the canonical set of agent utterances + that should occur when the agent is working + properly. + creation_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the test was created. + last_test_result (google.cloud.dialogflowcx_v3.types.TestCaseResult): + The latest test result. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + tags = proto.RepeatedField( + proto.STRING, + number=2, + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + notes = proto.Field( + proto.STRING, + number=4, + ) + test_config = proto.Field( + proto.MESSAGE, + number=13, + message='TestConfig', + ) + test_case_conversation_turns = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='ConversationTurn', + ) + creation_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + last_test_result = proto.Field( + proto.MESSAGE, + number=12, + message='TestCaseResult', + ) + + +class TestCaseResult(proto.Message): + r"""Represents a result from running a test case in an agent + environment. + + Attributes: + name (str): + The resource name for the test case result. Format: + ``projects//locations//agents//testCases/ /results/``. + environment (str): + Environment where the test was run. If not + set, it indicates the draft environment. + conversation_turns (Sequence[google.cloud.dialogflowcx_v3.types.ConversationTurn]): + The conversation turns uttered during the + test case replay in chronological order. + test_result (google.cloud.dialogflowcx_v3.types.TestResult): + Whether the test case passed in the agent + environment. + test_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the test was run. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.STRING, + number=2, + ) + conversation_turns = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ConversationTurn', + ) + test_result = proto.Field( + proto.ENUM, + number=4, + enum='TestResult', + ) + test_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class TestConfig(proto.Message): + r"""Represents configurations for a test case. + Attributes: + tracking_parameters (Sequence[str]): + Session parameters to be compared when + calculating differences. + flow (str): + Flow name. If not set, default start flow is assumed. + Format: + ``projects//locations//agents//flows/``. + """ + + tracking_parameters = proto.RepeatedField( + proto.STRING, + number=1, + ) + flow = proto.Field( + proto.STRING, + number=2, + ) + + +class ConversationTurn(proto.Message): + r"""One interaction between a human and virtual agent. The human + provides some input and the virtual agent provides a response. + + Attributes: + user_input (google.cloud.dialogflowcx_v3.types.ConversationTurn.UserInput): + The user input. + virtual_agent_output (google.cloud.dialogflowcx_v3.types.ConversationTurn.VirtualAgentOutput): + The virtual agent output. + """ + + class UserInput(proto.Message): + r"""The input from the human user. + Attributes: + input (google.cloud.dialogflowcx_v3.types.QueryInput): + Supports [text + input][google.cloud.dialogflow.cx.v3.QueryInput.text], + [event + input][google.cloud.dialogflow.cx.v3.QueryInput.event], + [dtmf input][google.cloud.dialogflow.cx.v3.QueryInput.dtmf] + in the test case. + injected_parameters (google.protobuf.struct_pb2.Struct): + Parameters that need to be injected into the + conversation during intent detection. + is_webhook_enabled (bool): + If webhooks should be allowed to trigger in + response to the user utterance. Often if + parameters are injected, webhooks should not be + enabled. + """ + + input = proto.Field( + proto.MESSAGE, + number=5, + message=session.QueryInput, + ) + injected_parameters = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + is_webhook_enabled = proto.Field( + proto.BOOL, + number=3, + ) + + class VirtualAgentOutput(proto.Message): + r"""The output from the virtual agent. + Attributes: + session_parameters (google.protobuf.struct_pb2.Struct): + The session parameters available to the bot + at this point. + differences (Sequence[google.cloud.dialogflowcx_v3.types.TestRunDifference]): + Output only. If this is part of a [result conversation + turn][TestCaseResult.conversation_turns], the list of + differences between the original run and the replay for this + output, if any. + diagnostic_info (google.protobuf.struct_pb2.Struct): + Required. Input only. The diagnostic + [info][Session.DetectIntentResponse.QueryResult.diagnostic_info] + output for the turn. + triggered_intent (google.cloud.dialogflowcx_v3.types.Intent): + The [Intent][google.cloud.dialogflow.cx.v3.Intent] that + triggered the response. Only name and displayName will be + set. + current_page (google.cloud.dialogflowcx_v3.types.Page): + The [Page][google.cloud.dialogflow.cx.v3.Page] on which the + utterance was spoken. Only name and displayName will be set. + text_responses (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage.Text]): + The + [text][google.cloud.dialogflow.cx.v3.ResponseMessage.Text] + responses from the agent for the turn. + status (google.rpc.status_pb2.Status): + Response error from the agent in the test + result. If set, other output is empty. + """ + + session_parameters = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + differences = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='TestRunDifference', + ) + diagnostic_info = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + triggered_intent = proto.Field( + proto.MESSAGE, + number=7, + message=gcdc_intent.Intent, + ) + current_page = proto.Field( + proto.MESSAGE, + number=8, + message=gcdc_page.Page, + ) + text_responses = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=response_message.ResponseMessage.Text, + ) + status = proto.Field( + proto.MESSAGE, + number=10, + message=status_pb2.Status, + ) + + user_input = proto.Field( + proto.MESSAGE, + number=1, + message=UserInput, + ) + virtual_agent_output = proto.Field( + proto.MESSAGE, + number=2, + message=VirtualAgentOutput, + ) + + +class TestRunDifference(proto.Message): + r"""The description of differences between original and replayed + agent output. + + Attributes: + type_ (google.cloud.dialogflowcx_v3.types.TestRunDifference.DiffType): + The type of diff. + description (str): + A description of the diff, showing the actual + output vs expected output. + """ + class DiffType(proto.Enum): + r"""What part of the message replay differs from the test case.""" + DIFF_TYPE_UNSPECIFIED = 0 + INTENT = 1 + PAGE = 2 + PARAMETERS = 3 + UTTERANCE = 4 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum=DiffType, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + + +class TransitionCoverage(proto.Message): + r"""Transition coverage represents the percentage of all possible + page transitions (page-level transition routes and event + handlers, excluding transition route groups) present within any + of a parent's test cases. + + Attributes: + transitions (Sequence[google.cloud.dialogflowcx_v3.types.TransitionCoverage.Transition]): + The list of Transitions present in the agent. + coverage_score (float): + The percent of transitions in the agent that + are covered. + """ + + class TransitionNode(proto.Message): + r"""The source or target of a transition. + Attributes: + page (google.cloud.dialogflowcx_v3.types.Page): + Indicates a transition to a + [Page][google.cloud.dialogflow.cx.v3.Page]. Only some fields + such as name and displayname will be set. + flow (google.cloud.dialogflowcx_v3.types.Flow): + Indicates a transition to a + [Flow][google.cloud.dialogflow.cx.v3.Flow]. Only some fields + such as name and displayname will be set. + """ + + page = proto.Field( + proto.MESSAGE, + number=1, + oneof='kind', + message=gcdc_page.Page, + ) + flow = proto.Field( + proto.MESSAGE, + number=2, + oneof='kind', + message=gcdc_flow.Flow, + ) + + class Transition(proto.Message): + r"""A transition in a page. + Attributes: + source (google.cloud.dialogflowcx_v3.types.TransitionCoverage.TransitionNode): + The start node of a transition. + index (int): + The index of a transition in the transition + list. Starting from 0. + target (google.cloud.dialogflowcx_v3.types.TransitionCoverage.TransitionNode): + The end node of a transition. + covered (bool): + Whether or not the transition is covered by + at least one of the agent's test cases. + transition_route (google.cloud.dialogflowcx_v3.types.TransitionRoute): + Intent route or condition route. + event_handler (google.cloud.dialogflowcx_v3.types.EventHandler): + Event handler. + """ + + source = proto.Field( + proto.MESSAGE, + number=1, + message='TransitionCoverage.TransitionNode', + ) + index = proto.Field( + proto.INT32, + number=4, + ) + target = proto.Field( + proto.MESSAGE, + number=2, + message='TransitionCoverage.TransitionNode', + ) + covered = proto.Field( + proto.BOOL, + number=3, + ) + transition_route = proto.Field( + proto.MESSAGE, + number=5, + oneof='detail', + message=gcdc_page.TransitionRoute, + ) + event_handler = proto.Field( + proto.MESSAGE, + number=6, + oneof='detail', + message=gcdc_page.EventHandler, + ) + + transitions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Transition, + ) + coverage_score = proto.Field( + proto.FLOAT, + number=2, + ) + + +class TransitionRouteGroupCoverage(proto.Message): + r"""Transition route group coverage represents the percentage of + all possible transition routes present within any of a parent's + test cases. The results are grouped by the transition route + group. + + Attributes: + coverages (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRouteGroupCoverage.Coverage]): + Transition route group coverages. + coverage_score (float): + The percent of transition routes in all the + transition route groups that are covered. + """ + + class Coverage(proto.Message): + r"""Coverage result message for one transition route group. + Attributes: + route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): + Transition route group metadata. Only name + and displayName will be set. + transitions (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRouteGroupCoverage.Coverage.Transition]): + The list of transition routes and coverage in + the transition route group. + coverage_score (float): + The percent of transition routes in the + transition route group that are covered. + """ + + class Transition(proto.Message): + r"""A transition coverage in a transition route group. + Attributes: + transition_route (google.cloud.dialogflowcx_v3.types.TransitionRoute): + Intent route or condition route. + covered (bool): + Whether or not the transition route is + covered by at least one of the agent's test + cases. + """ + + transition_route = proto.Field( + proto.MESSAGE, + number=1, + message=gcdc_page.TransitionRoute, + ) + covered = proto.Field( + proto.BOOL, + number=2, + ) + + route_group = proto.Field( + proto.MESSAGE, + number=1, + message=transition_route_group.TransitionRouteGroup, + ) + transitions = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='TransitionRouteGroupCoverage.Coverage.Transition', + ) + coverage_score = proto.Field( + proto.FLOAT, + number=3, + ) + + coverages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Coverage, + ) + coverage_score = proto.Field( + proto.FLOAT, + number=2, + ) + + +class IntentCoverage(proto.Message): + r"""Intent coverage represents the percentage of all possible + intents in the agent that are triggered in any of a parent's + test cases. + + Attributes: + intents (Sequence[google.cloud.dialogflowcx_v3.types.IntentCoverage.Intent]): + The list of Intents present in the agent + coverage_score (float): + The percent of intents in the agent that are + covered. + """ + + class Intent(proto.Message): + r"""The agent's intent. + Attributes: + intent (str): + The intent full resource name + covered (bool): + Whether or not the intent is covered by at + least one of the agent's test cases. + """ + + intent = proto.Field( + proto.STRING, + number=1, + ) + covered = proto.Field( + proto.BOOL, + number=2, + ) + + intents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Intent, + ) + coverage_score = proto.Field( + proto.FLOAT, + number=2, + ) + + +class CalculateCoverageRequest(proto.Message): + r"""The request message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + + Attributes: + agent (str): + Required. The agent to calculate coverage for. Format: + ``projects//locations//agents/``. + type_ (google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest.CoverageType): + Required. The type of coverage requested. + """ + class CoverageType(proto.Enum): + r"""The type of coverage score requested.""" + COVERAGE_TYPE_UNSPECIFIED = 0 + INTENT = 1 + PAGE_TRANSITION = 2 + TRANSITION_ROUTE_GROUP = 3 + + agent = proto.Field( + proto.STRING, + number=3, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum=CoverageType, + ) + + +class CalculateCoverageResponse(proto.Message): + r"""The response message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. + + Attributes: + agent (str): + The agent to calculate coverage for. Format: + ``projects//locations//agents/``. + intent_coverage (google.cloud.dialogflowcx_v3.types.IntentCoverage): + Intent coverage. + transition_coverage (google.cloud.dialogflowcx_v3.types.TransitionCoverage): + Transition (excluding transition route + groups) coverage. + route_group_coverage (google.cloud.dialogflowcx_v3.types.TransitionRouteGroupCoverage): + Transition route group coverage. + """ + + agent = proto.Field( + proto.STRING, + number=5, + ) + intent_coverage = proto.Field( + proto.MESSAGE, + number=2, + oneof='coverage_type', + message='IntentCoverage', + ) + transition_coverage = proto.Field( + proto.MESSAGE, + number=4, + oneof='coverage_type', + message='TransitionCoverage', + ) + route_group_coverage = proto.Field( + proto.MESSAGE, + number=6, + oneof='coverage_type', + message='TransitionRouteGroupCoverage', + ) + + +class ListTestCasesRequest(proto.Message): + r"""The request message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. + + Attributes: + parent (str): + Required. The agent to list all pages for. Format: + ``projects//locations//agents/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20. Note that when + TestCaseView = FULL, the maximum page size + allowed is 20. When TestCaseView = BASIC, the + maximum page size allowed is 500. + page_token (str): + The next_page_token value returned from a previous list + request. + view (google.cloud.dialogflowcx_v3.types.ListTestCasesRequest.TestCaseView): + Specifies whether response should include all + fields or just the metadata. + """ + class TestCaseView(proto.Enum): + r"""Specifies how much test case information to include in the + response. + """ + TEST_CASE_VIEW_UNSPECIFIED = 0 + BASIC = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + view = proto.Field( + proto.ENUM, + number=4, + enum=TestCaseView, + ) + + +class ListTestCasesResponse(proto.Message): + r"""The response message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. + + Attributes: + test_cases (Sequence[google.cloud.dialogflowcx_v3.types.TestCase]): + The list of test cases. 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 + + test_cases = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TestCase', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class BatchDeleteTestCasesRequest(proto.Message): + r"""The request message for + [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases]. + + Attributes: + parent (str): + Required. The agent to delete test cases from. Format: + ``projects//locations//agents/``. + names (Sequence[str]): + Required. Format of test case names: + ``projects//locations/ /agents//testCases/``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + names = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateTestCaseRequest(proto.Message): + r"""The request message for + [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase]. + + Attributes: + parent (str): + Required. The agent to create the test case for. Format: + ``projects//locations//agents/``. + test_case (google.cloud.dialogflowcx_v3.types.TestCase): + Required. The test case to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + test_case = proto.Field( + proto.MESSAGE, + number=2, + message='TestCase', + ) + + +class UpdateTestCaseRequest(proto.Message): + r"""The request message for + [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase]. + + Attributes: + test_case (google.cloud.dialogflowcx_v3.types.TestCase): + Required. The test case to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to specify which fields should be + updated. The + [``creationTime``][google.cloud.dialogflow.cx.v3.TestCase.creation_time] + and + [``lastTestResult``][google.cloud.dialogflow.cx.v3.TestCase.last_test_result] + cannot be updated. + """ + + test_case = proto.Field( + proto.MESSAGE, + number=1, + message='TestCase', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetTestCaseRequest(proto.Message): + r"""The request message for + [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3.TestCases.GetTestCase]. + + Attributes: + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class RunTestCaseRequest(proto.Message): + r"""The request message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. + + Attributes: + name (str): + Required. Format of test case name to run: + ``projects//locations/ /agents//testCases/``. + environment (str): + Optional. Environment name. If not set, draft environment is + assumed. Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.STRING, + number=2, + ) + + +class RunTestCaseResponse(proto.Message): + r"""The response message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. + + Attributes: + result (google.cloud.dialogflowcx_v3.types.TestCaseResult): + The result. + """ + + result = proto.Field( + proto.MESSAGE, + number=2, + message='TestCaseResult', + ) + + +class RunTestCaseMetadata(proto.Message): + r"""Metadata returned for the + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase] + long running operation. + """ + + +class BatchRunTestCasesRequest(proto.Message): + r"""The request message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. + + Attributes: + parent (str): + Required. Agent name. Format: + ``projects//locations//agents/ ``. + environment (str): + Optional. If not set, draft environment is assumed. Format: + ``projects//locations//agents//environments/``. + test_cases (Sequence[str]): + Required. Format: + ``projects//locations//agents//testCases/``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.STRING, + number=2, + ) + test_cases = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class BatchRunTestCasesResponse(proto.Message): + r"""The response message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. + + Attributes: + results (Sequence[google.cloud.dialogflowcx_v3.types.TestCaseResult]): + The test case results. The detailed [conversation + turns][google.cloud.dialogflow.cx.v3.TestCaseResult.conversation_turns] + are empty in this response. + """ + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TestCaseResult', + ) + + +class BatchRunTestCasesMetadata(proto.Message): + r"""Metadata returned for the + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases] + long running operation. + + Attributes: + errors (Sequence[google.cloud.dialogflowcx_v3.types.TestError]): + The test errors. + """ + + errors = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TestError', + ) + + +class TestError(proto.Message): + r"""Error info for running a test. + Attributes: + test_case (str): + The test case resource name. + status (google.rpc.status_pb2.Status): + The status associated with the test. + test_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the test was completed. + """ + + test_case = proto.Field( + proto.STRING, + number=1, + ) + status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + test_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class ImportTestCasesRequest(proto.Message): + r"""The request message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + + Attributes: + parent (str): + Required. The agent to import test cases to. Format: + ``projects//locations//agents/``. + gcs_uri (str): + The `Google Cloud + Storage `__ URI to + import test cases from. The format of this URI must be + ``gs:///``. + content (bytes): + Uncompressed raw byte content for test cases. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + gcs_uri = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + content = proto.Field( + proto.BYTES, + number=3, + oneof='source', + ) + + +class ImportTestCasesResponse(proto.Message): + r"""The response message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. + + Attributes: + names (Sequence[str]): + The unique identifiers of the new test cases. Format: + ``projects//locations//agents//testCases/``. + """ + + names = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class ImportTestCasesMetadata(proto.Message): + r"""Metadata returned for the + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases] + long running operation. + + Attributes: + errors (Sequence[google.cloud.dialogflowcx_v3.types.TestCaseError]): + Errors for failed test cases. + """ + + errors = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TestCaseError', + ) + + +class TestCaseError(proto.Message): + r"""Error info for importing a test. + Attributes: + test_case (google.cloud.dialogflowcx_v3.types.TestCase): + The test case. + status (google.rpc.status_pb2.Status): + The status associated with the test case. + """ + + test_case = proto.Field( + proto.MESSAGE, + number=1, + message='TestCase', + ) + status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + +class ExportTestCasesRequest(proto.Message): + r"""The request message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + + Attributes: + parent (str): + Required. The agent where to export test cases from. Format: + ``projects//locations//agents/``. + gcs_uri (str): + The `Google Cloud + Storage `__ URI to + export the test cases to. The format of this URI must be + ``gs:///``. If unspecified, the + serialized test cases is returned inline. + data_format (google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest.DataFormat): + The data format of the exported test cases. If not + specified, ``BLOB`` is assumed. + filter (str): + The filter expression used to filter exported test cases, + see `API Filtering `__. The expression + is case insensitive and supports the following syntax: + + name = [OR name = ] ... + + For example: + + - "name = t1 OR name = t2" matches the test case with the + exact resource name "t1" or "t2". + """ + class DataFormat(proto.Enum): + r"""Data format of the exported test cases.""" + DATA_FORMAT_UNSPECIFIED = 0 + BLOB = 1 + JSON = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + gcs_uri = proto.Field( + proto.STRING, + number=2, + oneof='destination', + ) + data_format = proto.Field( + proto.ENUM, + number=3, + enum=DataFormat, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ExportTestCasesResponse(proto.Message): + r"""The response message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. + + Attributes: + gcs_uri (str): + The URI to a file containing the exported test cases. This + field is populated only if ``gcs_uri`` is specified in + [ExportTestCasesRequest][google.cloud.dialogflow.cx.v3.ExportTestCasesRequest]. + content (bytes): + Uncompressed raw byte content for test cases. + """ + + gcs_uri = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + content = proto.Field( + proto.BYTES, + number=2, + oneof='destination', + ) + + +class ExportTestCasesMetadata(proto.Message): + r"""Metadata returned for the + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases] + long running operation. + """ + + +class ListTestCaseResultsRequest(proto.Message): + r"""The request message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. + + Attributes: + parent (str): + Required. The test case to list results for. Format: + ``projects//locations//agents// testCases/``. + Specify a ``-`` as a wildcard for TestCase ID to list + results across multiple test cases. + 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. + filter (str): + The filter expression used to filter test case results. See + `API Filtering `__. + + The expression is case insensitive. Only 'AND' is supported + for logical operators. The supported syntax is listed below + in detail: + + [AND ] ... [AND latest] + + The supported fields and operators are: field operator + ``environment`` ``=``, ``IN`` (Use value ``draft`` for draft + environment) ``test_time`` ``>``, ``<`` + + ``latest`` only returns the latest test result in all + results for each test case. + + Examples: + + - "environment=draft AND latest" matches the latest test + result for each test case in the draft environment. + - "environment IN (e1,e2)" matches any test case results + with an environment resource name of either "e1" or "e2". + - "test_time > 1602540713" matches any test case results + with test time later than a unix timestamp in seconds + 1602540713. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListTestCaseResultsResponse(proto.Message): + r"""The response message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. + + Attributes: + test_case_results (Sequence[google.cloud.dialogflowcx_v3.types.TestCaseResult]): + The list of test case results. + 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 + + test_case_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TestCaseResult', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTestCaseResultRequest(proto.Message): + r"""The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. + + Attributes: + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/transition_route_group.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/transition_route_group.py new file mode 100644 index 00000000..134f5761 --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/transition_route_group.py @@ -0,0 +1,307 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import page +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'TransitionRouteGroup', + 'ListTransitionRouteGroupsRequest', + 'ListTransitionRouteGroupsResponse', + 'GetTransitionRouteGroupRequest', + 'CreateTransitionRouteGroupRequest', + 'UpdateTransitionRouteGroupRequest', + 'DeleteTransitionRouteGroupRequest', + }, +) + + +class TransitionRouteGroup(proto.Message): + r"""An TransitionRouteGroup represents a group of + [``TransitionRoutes``][google.cloud.dialogflow.cx.v3.TransitionRoute] + to be used by a [Page][google.cloud.dialogflow.cx.v3.Page]. + + Attributes: + name (str): + The unique identifier of the transition route group. + [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup] + populates the name automatically. Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + display_name (str): + Required. The human-readable name of the transition route + group, unique within the + [Agent][google.cloud.dialogflow.cx.v3.Agent]. The display + name can be no longer than 30 characters. + transition_routes (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRoute]): + Transition routes associated with the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + transition_routes = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=page.TransitionRoute, + ) + + +class ListTransitionRouteGroupsRequest(proto.Message): + r"""The request message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. + + Attributes: + parent (str): + Required. The flow to list all transition route groups for. + Format: + ``projects//locations//agents//flows/``. + 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. + language_code (str): + The language to list transition route groups for. The + following fields are language dependent: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class ListTransitionRouteGroupsResponse(proto.Message): + r"""The response message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. + + Attributes: + transition_route_groups (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRouteGroup]): + The list of transition route groups. There will be a maximum + number of items returned based on the page_size field in the + request. The list may in some cases be empty or contain + fewer entries than page_size even if this isn't the last + page. + 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 + + transition_route_groups = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TransitionRouteGroup', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTransitionRouteGroupRequest(proto.Message): + r"""The request message for + [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.GetTransitionRouteGroup]. + + Attributes: + name (str): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. + Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + language_code (str): + The language to retrieve the transition route group for. The + following fields are language dependent: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateTransitionRouteGroupRequest(proto.Message): + r"""The request message for + [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup]. + + Attributes: + parent (str): + Required. The flow to create an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + for. Format: + ``projects//locations//agents//flows/``. + transition_route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): + Required. The transition route group to + create. + language_code (str): + The language of the following fields in + ``TransitionRouteGroup``: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + transition_route_group = proto.Field( + proto.MESSAGE, + number=2, + message='TransitionRouteGroup', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateTransitionRouteGroupRequest(proto.Message): + r"""The request message for + [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.UpdateTransitionRouteGroup]. + + Attributes: + transition_route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): + Required. The transition route group to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + language_code (str): + The language of the following fields in + ``TransitionRouteGroup``: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + transition_route_group = proto.Field( + proto.MESSAGE, + number=1, + message='TransitionRouteGroup', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteTransitionRouteGroupRequest(proto.Message): + r"""The request message for + [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.DeleteTransitionRouteGroup]. + + Attributes: + name (str): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] + to delete. Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + force (bool): + This field has no effect for transition route group that no + page is using. If the transition route group is referenced + by any page: + + - If ``force`` is set to false, an error will be returned + with message indicating pages that reference the + transition route group. + - If ``force`` is set to true, Dialogflow will remove the + transition route group, as well as any reference to it. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/validation_message.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/validation_message.py new file mode 100644 index 00000000..83857e1b --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/validation_message.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cx.v3', + manifest={ + 'ValidationMessage', + 'ResourceName', + }, +) + + +class ValidationMessage(proto.Message): + r"""Agent/flow validation message. + Attributes: + resource_type (google.cloud.dialogflowcx_v3.types.ValidationMessage.ResourceType): + The type of the resources where the message + is found. + resources (Sequence[str]): + The names of the resources where the message + is found. + resource_names (Sequence[google.cloud.dialogflowcx_v3.types.ResourceName]): + The resource names of the resources where the + message is found. + severity (google.cloud.dialogflowcx_v3.types.ValidationMessage.Severity): + Indicates the severity of the message. + detail (str): + The message detail. + """ + class ResourceType(proto.Enum): + r"""Resource types.""" + RESOURCE_TYPE_UNSPECIFIED = 0 + AGENT = 1 + INTENT = 2 + INTENT_TRAINING_PHRASE = 8 + INTENT_PARAMETER = 9 + INTENTS = 10 + INTENT_TRAINING_PHRASES = 11 + ENTITY_TYPE = 3 + ENTITY_TYPES = 12 + WEBHOOK = 4 + FLOW = 5 + PAGE = 6 + PAGES = 13 + TRANSITION_ROUTE_GROUP = 7 + + class Severity(proto.Enum): + r"""Severity level.""" + SEVERITY_UNSPECIFIED = 0 + INFO = 1 + WARNING = 2 + ERROR = 3 + + resource_type = proto.Field( + proto.ENUM, + number=1, + enum=ResourceType, + ) + resources = proto.RepeatedField( + proto.STRING, + number=2, + ) + resource_names = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ResourceName', + ) + severity = proto.Field( + proto.ENUM, + number=3, + enum=Severity, + ) + detail = proto.Field( + proto.STRING, + number=4, + ) + + +class ResourceName(proto.Message): + r"""Resource name and display name. + Attributes: + name (str): + Name. + display_name (str): + Display name. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/version.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/version.py new file mode 100644 index 00000000..b5e9868f --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/version.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 proto # type: ignore + +from google.cloud.dialogflowcx_v3.types import flow +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'CreateVersionOperationMetadata', + 'Version', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'GetVersionRequest', + 'CreateVersionRequest', + 'UpdateVersionRequest', + 'DeleteVersionRequest', + 'LoadVersionRequest', + }, +) + + +class CreateVersionOperationMetadata(proto.Message): + r"""Metadata associated with the long running operation for + [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. + + Attributes: + version (str): + Name of the created version. Format: + ``projects//locations//agents//flows//versions/``. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + + +class Version(proto.Message): + r"""Represents a version of a flow. + Attributes: + name (str): + Format: projects//locations//agents//flows//versions/. + Version ID is a self-increasing number generated + by Dialogflow upon version creation. + display_name (str): + Required. The human-readable name of the + version. Limit of 64 characters. + description (str): + The description of the version. The maximum + length is 500 characters. If exceeded, the + request is rejected. + nlu_settings (google.cloud.dialogflowcx_v3.types.NluSettings): + Output only. The NLU settings of the flow at + version creation. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time of the version. + state (google.cloud.dialogflowcx_v3.types.Version.State): + Output only. The state of this version. This + field is read-only and cannot be set by create + and update methods. + """ + class State(proto.Enum): + r"""The state of the version.""" + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + nlu_settings = proto.Field( + proto.MESSAGE, + number=4, + message=flow.NluSettings, + ) + create_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + state = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + + +class ListVersionsRequest(proto.Message): + r"""The request message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. + + Attributes: + parent (str): + Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] to + list all versions for. Format: + ``projects//locations//agents//flows/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 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 ListVersionsResponse(proto.Message): + r"""The response message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. + + Attributes: + versions (Sequence[google.cloud.dialogflowcx_v3.types.Version]): + A list of versions. There will be a maximum number of items + returned based on the page_size field in the request. The + list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + 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.cx.v3.Versions.GetVersion]. + + Attributes: + name (str): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3.Version]. Format: + ``projects//locations//agents//flows//versions/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateVersionRequest(proto.Message): + r"""The request message for + [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. + + Attributes: + parent (str): + Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] to + create an [Version][google.cloud.dialogflow.cx.v3.Version] + for. Format: + ``projects//locations//agents//flows/``. + version (google.cloud.dialogflowcx_v3.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.cx.v3.Versions.UpdateVersion]. + + Attributes: + version (google.cloud.dialogflowcx_v3.types.Version): + Required. The version to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields get updated. + Currently only ``description`` and ``display_name`` can be + 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.cx.v3.Versions.DeleteVersion]. + + Attributes: + name (str): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3.Version] to delete. + Format: + ``projects//locations//agents//flows//versions/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class LoadVersionRequest(proto.Message): + r"""The request message for + [Versions.LoadVersion][google.cloud.dialogflow.cx.v3.Versions.LoadVersion]. + + Attributes: + name (str): + Required. The + [Version][google.cloud.dialogflow.cx.v3.Version] to be + loaded to draft flow. Format: + ``projects//locations//agents//flows//versions/``. + allow_override_agent_resources (bool): + This field is used to prevent accidental overwrite of other + agent resources, which can potentially impact other flow's + behavior. If ``allow_override_agent_resources`` is false, + conflicted agent-level resources will not be overridden + (i.e. intents, entities, webhooks). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + allow_override_agent_resources = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/webhook.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/webhook.py new file mode 100644 index 00000000..480caa8e --- /dev/null +++ b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/webhook.py @@ -0,0 +1,791 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import response_message +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3', + manifest={ + 'Webhook', + 'ListWebhooksRequest', + 'ListWebhooksResponse', + 'GetWebhookRequest', + 'CreateWebhookRequest', + 'UpdateWebhookRequest', + 'DeleteWebhookRequest', + 'WebhookRequest', + 'WebhookResponse', + 'PageInfo', + 'SessionInfo', + }, +) + + +class Webhook(proto.Message): + r"""Webhooks host the developer's business logic. During a + session, webhooks allow the developer to use the data extracted + by Dialogflow's natural language processing to generate dynamic + responses, validate collected data, or trigger actions on the + backend. + + Attributes: + name (str): + The unique identifier of the webhook. Required for the + [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook] + method. + [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook] + populates the name automatically. Format: + ``projects//locations//agents//webhooks/``. + display_name (str): + Required. The human-readable name of the + webhook, unique within the agent. + generic_web_service (google.cloud.dialogflowcx_v3.types.Webhook.GenericWebService): + Configuration for a generic web service. + service_directory (google.cloud.dialogflowcx_v3.types.Webhook.ServiceDirectoryConfig): + Configuration for a `Service + Directory `__ + service. + timeout (google.protobuf.duration_pb2.Duration): + Webhook execution timeout. Execution is + considered failed if Dialogflow doesn't receive + a response from webhook at the end of the + timeout period. Defaults to 5 seconds, maximum + allowed timeout is 30 seconds. + disabled (bool): + Indicates whether the webhook is disabled. + """ + + class GenericWebService(proto.Message): + r"""Represents configuration for a generic web service. + Attributes: + uri (str): + Required. The webhook 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.dialogflowcx_v3.types.Webhook.GenericWebService.RequestHeadersEntry]): + The HTTP request headers to send together + with webhook requests. + """ + + 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, + ) + + class ServiceDirectoryConfig(proto.Message): + r"""Represents configuration for a `Service + Directory `__ service. + + Attributes: + service (str): + Required. The name of `Service + Directory `__ + service. Format: + ``projects//locations//namespaces//services/``. + ``Location ID`` of the service directory must be the same as + the location of the agent. + generic_web_service (google.cloud.dialogflowcx_v3.types.Webhook.GenericWebService): + Generic Service configuration of this + webhook. + """ + + service = proto.Field( + proto.STRING, + number=1, + ) + generic_web_service = proto.Field( + proto.MESSAGE, + number=2, + message='Webhook.GenericWebService', + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + generic_web_service = proto.Field( + proto.MESSAGE, + number=4, + oneof='webhook', + message=GenericWebService, + ) + service_directory = proto.Field( + proto.MESSAGE, + number=7, + oneof='webhook', + message=ServiceDirectoryConfig, + ) + timeout = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + disabled = proto.Field( + proto.BOOL, + number=5, + ) + + +class ListWebhooksRequest(proto.Message): + r"""The request message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. + + Attributes: + parent (str): + Required. The agent to list all webhooks for. Format: + ``projects//locations//agents/``. + 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 ListWebhooksResponse(proto.Message): + r"""The response message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. + + Attributes: + webhooks (Sequence[google.cloud.dialogflowcx_v3.types.Webhook]): + The list of webhooks. 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 + + webhooks = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Webhook', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetWebhookRequest(proto.Message): + r"""The request message for + [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3.Webhooks.GetWebhook]. + + Attributes: + name (str): + Required. The name of the webhook. Format: + ``projects//locations//agents//webhooks/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateWebhookRequest(proto.Message): + r"""The request message for + [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook]. + + Attributes: + parent (str): + Required. The agent to create a webhook for. Format: + ``projects//locations//agents/``. + webhook (google.cloud.dialogflowcx_v3.types.Webhook): + Required. The webhook to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + webhook = proto.Field( + proto.MESSAGE, + number=2, + message='Webhook', + ) + + +class UpdateWebhookRequest(proto.Message): + r"""The request message for + [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook]. + + Attributes: + webhook (google.cloud.dialogflowcx_v3.types.Webhook): + Required. The webhook to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + updated. + """ + + webhook = proto.Field( + proto.MESSAGE, + number=1, + message='Webhook', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteWebhookRequest(proto.Message): + r"""The request message for + [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3.Webhooks.DeleteWebhook]. + + Attributes: + name (str): + Required. The name of the webhook to delete. Format: + ``projects//locations//agents//webhooks/``. + force (bool): + This field has no effect for webhook not being used. For + webhooks that are used by pages/flows/transition route + groups: + + - If ``force`` is set to false, an error will be returned + with message indicating the referenced resources. + - If ``force`` is set to true, Dialogflow will remove the + webhook, as well as any references to the webhook (i.e. + [Webhook][google.cloud.dialogflow.cx.v3.Fulfillment.webhook] + and + [tag][google.cloud.dialogflow.cx.v3.Fulfillment.tag]in + fulfillments that point to this webhook will be removed). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class WebhookRequest(proto.Message): + r"""The request message for a webhook call. The request is sent + as a JSON object and the field names will be presented in camel + cases. + + Attributes: + detect_intent_response_id (str): + Always present. The unique identifier of the + [DetectIntentResponse][google.cloud.dialogflow.cx.v3.DetectIntentResponse] + that will be returned to the API caller. + text (str): + If [natural language + text][google.cloud.dialogflow.cx.v3.TextInput] was provided + as input, this field will contain a copy of the text. + trigger_intent (str): + If an [intent][google.cloud.dialogflow.cx.v3.IntentInput] + was provided as input, this field will contain a copy of the + intent identifier. Format: + ``projects//locations//agents//intents/``. + transcript (str): + If [natural language speech + audio][google.cloud.dialogflow.cx.v3.AudioInput] was + provided as input, this field will contain the transcript + for the audio. + trigger_event (str): + If an [event][google.cloud.dialogflow.cx.v3.EventInput] was + provided as input, this field will contain the name of the + event. + language_code (str): + The language code specified in the [original + request][QueryInput.language_code]. + fulfillment_info (google.cloud.dialogflowcx_v3.types.WebhookRequest.FulfillmentInfo): + Always present. Information about the + fulfillment that triggered this webhook call. + intent_info (google.cloud.dialogflowcx_v3.types.WebhookRequest.IntentInfo): + Information about the last matched intent. + page_info (google.cloud.dialogflowcx_v3.types.PageInfo): + Information about page status. + session_info (google.cloud.dialogflowcx_v3.types.SessionInfo): + Information about session status. + messages (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage]): + The list of rich message responses to present to the user. + Webhook can choose to append or replace this list in + [WebhookResponse.fulfillment_response][google.cloud.dialogflow.cx.v3.WebhookResponse.fulfillment_response]; + payload (google.protobuf.struct_pb2.Struct): + Custom data set in + [QueryParameters.payload][google.cloud.dialogflow.cx.v3.QueryParameters.payload]. + sentiment_analysis_result (google.cloud.dialogflowcx_v3.types.WebhookRequest.SentimentAnalysisResult): + The sentiment analysis result of the current + user request. The field is filled when sentiment + analysis is configured to be enabled for the + request. + """ + + class FulfillmentInfo(proto.Message): + r"""Represents fulfillment information communicated to the + webhook. + + Attributes: + tag (str): + Always present. The tag used to identify + which fulfillment is being called. + """ + + tag = proto.Field( + proto.STRING, + number=1, + ) + + class IntentInfo(proto.Message): + r"""Represents intent information communicated to the webhook. + Attributes: + last_matched_intent (str): + Always present. The unique identifier of the last matched + [intent][google.cloud.dialogflow.cx.v3.Intent]. Format: + ``projects//locations//agents//intents/``. + display_name (str): + Always present. The display name of the last matched + [intent][google.cloud.dialogflow.cx.v3.Intent]. + parameters (Sequence[google.cloud.dialogflowcx_v3.types.WebhookRequest.IntentInfo.ParametersEntry]): + Parameters identified as a result of intent + matching. This is a map of the name of the + identified parameter to the value of the + parameter identified from the user's utterance. + All parameters defined in the matched intent + that are identified will be surfaced here. + confidence (float): + The confidence of the matched intent. Values + range from 0.0 (completely uncertain) to 1.0 + (completely certain). + """ + + class IntentParameterValue(proto.Message): + r"""Represents a value for an intent parameter. + Attributes: + original_value (str): + Always present. Original text value extracted + from user utterance. + resolved_value (google.protobuf.struct_pb2.Value): + Always present. Structured value for the + parameter extracted from user utterance. + """ + + original_value = proto.Field( + proto.STRING, + number=1, + ) + resolved_value = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + last_matched_intent = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + parameters = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='WebhookRequest.IntentInfo.IntentParameterValue', + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + + class SentimentAnalysisResult(proto.Message): + r"""Represents the result of sentiment analysis. + 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, + ) + + detect_intent_response_id = proto.Field( + proto.STRING, + number=1, + ) + text = proto.Field( + proto.STRING, + number=10, + oneof='query', + ) + trigger_intent = proto.Field( + proto.STRING, + number=11, + oneof='query', + ) + transcript = proto.Field( + proto.STRING, + number=12, + oneof='query', + ) + trigger_event = proto.Field( + proto.STRING, + number=14, + oneof='query', + ) + language_code = proto.Field( + proto.STRING, + number=15, + ) + fulfillment_info = proto.Field( + proto.MESSAGE, + number=6, + message=FulfillmentInfo, + ) + intent_info = proto.Field( + proto.MESSAGE, + number=3, + message=IntentInfo, + ) + page_info = proto.Field( + proto.MESSAGE, + number=4, + message='PageInfo', + ) + session_info = proto.Field( + proto.MESSAGE, + number=5, + message='SessionInfo', + ) + messages = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=response_message.ResponseMessage, + ) + payload = proto.Field( + proto.MESSAGE, + number=8, + message=struct_pb2.Struct, + ) + sentiment_analysis_result = proto.Field( + proto.MESSAGE, + number=9, + message=SentimentAnalysisResult, + ) + + +class WebhookResponse(proto.Message): + r"""The response message for a webhook call. + Attributes: + fulfillment_response (google.cloud.dialogflowcx_v3.types.WebhookResponse.FulfillmentResponse): + The fulfillment response to send to the user. + This field can be omitted by the webhook if it + does not intend to send any response to the + user. + page_info (google.cloud.dialogflowcx_v3.types.PageInfo): + Information about page status. This field can + be omitted by the webhook if it does not intend + to modify page status. + session_info (google.cloud.dialogflowcx_v3.types.SessionInfo): + Information about session status. This field + can be omitted by the webhook if it does not + intend to modify session status. + payload (google.protobuf.struct_pb2.Struct): + Value to append directly to + [QueryResult.webhook_payloads][google.cloud.dialogflow.cx.v3.QueryResult.webhook_payloads]. + target_page (str): + The target page to transition to. Format: + ``projects//locations//agents//flows//pages/``. + target_flow (str): + The target flow to transition to. Format: + ``projects//locations//agents//flows/``. + """ + + class FulfillmentResponse(proto.Message): + r"""Represents a fulfillment response to the user. + Attributes: + messages (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage]): + The list of rich message responses to present + to the user. + merge_behavior (google.cloud.dialogflowcx_v3.types.WebhookResponse.FulfillmentResponse.MergeBehavior): + Merge behavior for ``messages``. + """ + class MergeBehavior(proto.Enum): + r"""Defines merge behavior for ``messages``.""" + MERGE_BEHAVIOR_UNSPECIFIED = 0 + APPEND = 1 + REPLACE = 2 + + messages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=response_message.ResponseMessage, + ) + merge_behavior = proto.Field( + proto.ENUM, + number=2, + enum='WebhookResponse.FulfillmentResponse.MergeBehavior', + ) + + fulfillment_response = proto.Field( + proto.MESSAGE, + number=1, + message=FulfillmentResponse, + ) + page_info = proto.Field( + proto.MESSAGE, + number=2, + message='PageInfo', + ) + session_info = proto.Field( + proto.MESSAGE, + number=3, + message='SessionInfo', + ) + payload = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + target_page = proto.Field( + proto.STRING, + number=5, + oneof='transition', + ) + target_flow = proto.Field( + proto.STRING, + number=6, + oneof='transition', + ) + + +class PageInfo(proto.Message): + r"""Represents page information communicated to and from the + webhook. + + Attributes: + current_page (str): + Always present for + [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. + Ignored for + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + The unique identifier of the current page. Format: + ``projects//locations//agents//flows//pages/``. + form_info (google.cloud.dialogflowcx_v3.types.PageInfo.FormInfo): + Optional for both + [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest] + and + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + Information about the form. + """ + + class FormInfo(proto.Message): + r"""Represents form information. + Attributes: + parameter_info (Sequence[google.cloud.dialogflowcx_v3.types.PageInfo.FormInfo.ParameterInfo]): + Optional for both + [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest] + and + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + The parameters contained in the form. Note that the webhook + cannot add or remove any form parameter. + """ + + class ParameterInfo(proto.Message): + r"""Represents parameter information. + Attributes: + display_name (str): + Always present for + [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. + Required for + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + The human-readable name of the parameter, unique within the + form. This field cannot be modified by the webhook. + required (bool): + Optional for both + [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest] + and + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + Indicates whether the parameter is required. Optional + parameters will not trigger prompts; however, they are + filled if the user specifies them. Required parameters must + be filled before form filling concludes. + state (google.cloud.dialogflowcx_v3.types.PageInfo.FormInfo.ParameterInfo.ParameterState): + Always present for + [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. + Required for + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + The state of the parameter. This field can be set to + [INVALID][google.cloud.dialogflow.cx.v3.PageInfo.FormInfo.ParameterInfo.ParameterState.INVALID] + by the webhook to invalidate the parameter; other values set + by the webhook will be ignored. + value (google.protobuf.struct_pb2.Value): + Optional for both + [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest] + and + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + The value of the parameter. This field can be set by the + webhook to change the parameter value. + just_collected (bool): + Optional for + [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. + Ignored for + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + Indicates if the parameter value was just collected on the + last conversation turn. + """ + class ParameterState(proto.Enum): + r"""Represents the state of a parameter.""" + PARAMETER_STATE_UNSPECIFIED = 0 + EMPTY = 1 + INVALID = 2 + FILLED = 3 + + display_name = proto.Field( + proto.STRING, + number=1, + ) + required = proto.Field( + proto.BOOL, + number=2, + ) + state = proto.Field( + proto.ENUM, + number=3, + enum='PageInfo.FormInfo.ParameterInfo.ParameterState', + ) + value = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Value, + ) + just_collected = proto.Field( + proto.BOOL, + number=5, + ) + + parameter_info = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='PageInfo.FormInfo.ParameterInfo', + ) + + current_page = proto.Field( + proto.STRING, + number=1, + ) + form_info = proto.Field( + proto.MESSAGE, + number=3, + message=FormInfo, + ) + + +class SessionInfo(proto.Message): + r"""Represents session information communicated to and from the + webhook. + + Attributes: + session (str): + Always present for + [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. + Ignored for + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + The unique identifier of the + [session][google.cloud.dialogflow.cx.v3.DetectIntentRequest.session]. + This field can be used by the webhook to identify a session. + Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/`` + if environment is specified. + parameters (Sequence[google.cloud.dialogflowcx_v3.types.SessionInfo.ParametersEntry]): + Optional for + [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. + Optional for + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + All parameters collected from forms and intents during the + session. Parameters can be created, updated, or removed by + the webhook. To remove a parameter from the session, the + webhook should explicitly set the parameter value to null in + [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. + The map is keyed by parameters' display names. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + parameters = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/mypy.ini b/owl-bot-staging/v3/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v3/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v3/noxfile.py b/owl-bot-staging/v3/noxfile.py new file mode 100644 index 00000000..2343cde2 --- /dev/null +++ b/owl-bot-staging/v3/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/dialogflowcx_v3/', + '--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/v3/scripts/fixup_dialogflowcx_v3_keywords.py b/owl-bot-staging/v3/scripts/fixup_dialogflowcx_v3_keywords.py new file mode 100644 index 00000000..c341e25f --- /dev/null +++ b/owl-bot-staging/v3/scripts/fixup_dialogflowcx_v3_keywords.py @@ -0,0 +1,264 @@ +#! /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 dialogflowcxCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_delete_test_cases': ('parent', 'names', ), + 'batch_run_test_cases': ('parent', 'test_cases', 'environment', ), + 'calculate_coverage': ('agent', 'type_', ), + 'create_agent': ('parent', 'agent', ), + 'create_entity_type': ('parent', 'entity_type', 'language_code', ), + 'create_environment': ('parent', 'environment', ), + 'create_experiment': ('parent', 'experiment', ), + 'create_flow': ('parent', 'flow', 'language_code', ), + 'create_intent': ('parent', 'intent', 'language_code', ), + 'create_page': ('parent', 'page', 'language_code', ), + 'create_security_settings': ('parent', 'security_settings', ), + 'create_session_entity_type': ('parent', 'session_entity_type', ), + 'create_test_case': ('parent', 'test_case', ), + 'create_transition_route_group': ('parent', 'transition_route_group', 'language_code', ), + 'create_version': ('parent', 'version', ), + 'create_webhook': ('parent', 'webhook', ), + 'delete_agent': ('name', ), + 'delete_entity_type': ('name', 'force', ), + 'delete_environment': ('name', ), + 'delete_experiment': ('name', ), + 'delete_flow': ('name', 'force', ), + 'delete_intent': ('name', ), + 'delete_page': ('name', 'force', ), + 'delete_security_settings': ('name', ), + 'delete_session_entity_type': ('name', ), + 'delete_transition_route_group': ('name', 'force', ), + 'delete_version': ('name', ), + 'delete_webhook': ('name', 'force', ), + 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', ), + 'export_agent': ('name', 'agent_uri', 'environment', ), + 'export_flow': ('name', 'flow_uri', 'include_referenced_flows', ), + 'export_test_cases': ('parent', 'gcs_uri', 'data_format', 'filter', ), + 'fulfill_intent': ('match_intent_request', 'match', 'output_audio_config', ), + 'get_agent': ('name', ), + 'get_agent_validation_result': ('name', 'language_code', ), + 'get_entity_type': ('name', 'language_code', ), + 'get_environment': ('name', ), + 'get_experiment': ('name', ), + 'get_flow': ('name', 'language_code', ), + 'get_flow_validation_result': ('name', 'language_code', ), + 'get_intent': ('name', 'language_code', ), + 'get_page': ('name', 'language_code', ), + 'get_security_settings': ('name', ), + 'get_session_entity_type': ('name', ), + 'get_test_case': ('name', ), + 'get_test_case_result': ('name', ), + 'get_transition_route_group': ('name', 'language_code', ), + 'get_version': ('name', ), + 'get_webhook': ('name', ), + 'import_flow': ('parent', 'flow_uri', 'flow_content', 'import_option', ), + 'import_test_cases': ('parent', 'gcs_uri', 'content', ), + 'list_agents': ('parent', 'page_size', 'page_token', ), + 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_experiments': ('parent', 'page_size', 'page_token', ), + 'list_flows': ('parent', 'page_size', 'page_token', 'language_code', ), + 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), + 'list_pages': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_security_settings': ('parent', 'page_size', 'page_token', ), + 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), + 'list_test_case_results': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_test_cases': ('parent', 'page_size', 'page_token', 'view', ), + 'list_transition_route_groups': ('parent', 'page_size', 'page_token', 'language_code', ), + 'list_versions': ('parent', 'page_size', 'page_token', ), + 'list_webhooks': ('parent', 'page_size', 'page_token', ), + 'load_version': ('name', 'allow_override_agent_resources', ), + 'lookup_environment_history': ('name', 'page_size', 'page_token', ), + 'match_intent': ('session', 'query_input', 'query_params', ), + 'restore_agent': ('name', 'agent_uri', 'agent_content', 'restore_option', ), + 'run_test_case': ('name', 'environment', ), + 'start_experiment': ('name', ), + 'stop_experiment': ('name', ), + 'streaming_detect_intent': ('query_input', 'session', 'query_params', 'output_audio_config', ), + 'train_flow': ('name', ), + 'update_agent': ('agent', 'update_mask', ), + 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), + 'update_environment': ('environment', 'update_mask', ), + 'update_experiment': ('experiment', 'update_mask', ), + 'update_flow': ('flow', 'update_mask', 'language_code', ), + 'update_intent': ('intent', 'language_code', 'update_mask', ), + 'update_page': ('page', 'language_code', 'update_mask', ), + 'update_security_settings': ('security_settings', 'update_mask', ), + 'update_session_entity_type': ('session_entity_type', 'update_mask', ), + 'update_test_case': ('test_case', 'update_mask', ), + 'update_transition_route_group': ('transition_route_group', 'update_mask', 'language_code', ), + 'update_version': ('version', 'update_mask', ), + 'update_webhook': ('webhook', 'update_mask', ), + 'validate_agent': ('name', 'language_code', ), + 'validate_flow': ('name', 'language_code', ), + } + + 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=dialogflowcxCallTransformer(), +): + """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 dialogflowcx 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/v3/setup.py b/owl-bot-staging/v3/setup.py new file mode 100644 index 00000000..18e33869 --- /dev/null +++ b/owl-bot-staging/v3/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-dialogflowcx', + 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/v3/tests/__init__.py b/owl-bot-staging/v3/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v3/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/v3/tests/unit/__init__.py b/owl-bot-staging/v3/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v3/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/v3/tests/unit/gapic/__init__.py b/owl-bot-staging/v3/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v3/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/v3/tests/unit/gapic/dialogflowcx_v3/__init__.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/__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/v3/tests/unit/gapic/dialogflowcx_v3/test_agents.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_agents.py new file mode 100644 index 00000000..9c692470 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_agents.py @@ -0,0 +1,3312 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.agents import AgentsAsyncClient +from google.cloud.dialogflowcx_v3.services.agents import AgentsClient +from google.cloud.dialogflowcx_v3.services.agents import pagers +from google.cloud.dialogflowcx_v3.services.agents import transports +from google.cloud.dialogflowcx_v3.services.agents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.agents.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import agent +from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3.types import flow +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3.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_list_agents(transport: str = 'grpc', request_type=agent.ListAgentsRequest): + 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.list_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.ListAgentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ListAgentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_agents_from_dict(): + test_list_agents(request_type=dict) + + +def test_list_agents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agents), + '__call__') as call: + client.list_agents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ListAgentsRequest() + + +@pytest.mark.asyncio +async def test_list_agents_async(transport: str = 'grpc_asyncio', request_type=agent.ListAgentsRequest): + 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.list_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ListAgentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_agents_async_from_dict(): + await test_list_agents_async(request_type=dict) + + +def test_list_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.ListAgentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agents), + '__call__') as call: + call.return_value = agent.ListAgentsResponse() + client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_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.ListAgentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse()) + await client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_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.list_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.ListAgentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_agents( + parent='parent_value', + ) + + # Establish that the 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_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.list_agents( + agent.ListAgentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_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.list_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.ListAgentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_list_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.list_agents( + agent.ListAgentsRequest(), + parent='parent_value', + ) + + +def test_list_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.list_agents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.ListAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_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_list_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.list_agents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.ListAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_list_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.list_agents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.ListAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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_list_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.list_agents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.ListAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_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_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( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + ) + response = client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +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( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + )) + response = await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +@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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + call.return_value = agent.Agent() + client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) + await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_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( + 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_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(), + name='name_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( + 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_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(), + name='name_value', + ) + + +def test_create_agent(transport: str = 'grpc', request_type=gcdc_agent.CreateAgentRequest): + 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.create_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + ) + response = client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.CreateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +def test_create_agent_from_dict(): + test_create_agent(request_type=dict) + + +def test_create_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agent), + '__call__') as call: + client.create_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.CreateAgentRequest() + + +@pytest.mark.asyncio +async def test_create_agent_async(transport: str = 'grpc_asyncio', request_type=gcdc_agent.CreateAgentRequest): + 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.create_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + )) + response = await client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.CreateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +@pytest.mark.asyncio +async def test_create_agent_async_from_dict(): + await test_create_agent_async(request_type=dict) + + +def test_create_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 = gcdc_agent.CreateAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_agent), + '__call__') as call: + call.return_value = gcdc_agent.Agent() + client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_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 = gcdc_agent.CreateAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) + await client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_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.create_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_agent( + parent='parent_value', + agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') + + +def test_create_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.create_agent( + gcdc_agent.CreateAgentRequest(), + parent='parent_value', + agent=gcdc_agent.Agent(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_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.create_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_agent( + parent='parent_value', + agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') + + +@pytest.mark.asyncio +async def test_create_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.create_agent( + gcdc_agent.CreateAgentRequest(), + parent='parent_value', + agent=gcdc_agent.Agent(name='name_value'), + ) + + +def test_update_agent(transport: str = 'grpc', request_type=gcdc_agent.UpdateAgentRequest): + 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.update_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + ) + response = client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.UpdateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +def test_update_agent_from_dict(): + test_update_agent(request_type=dict) + + +def test_update_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agent), + '__call__') as call: + client.update_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.UpdateAgentRequest() + + +@pytest.mark.asyncio +async def test_update_agent_async(transport: str = 'grpc_asyncio', request_type=gcdc_agent.UpdateAgentRequest): + 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.update_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + )) + response = await client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.UpdateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +@pytest.mark.asyncio +async def test_update_agent_async_from_dict(): + await test_update_agent_async(request_type=dict) + + +def test_update_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 = gcdc_agent.UpdateAgentRequest() + + request.agent.name = 'agent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_agent), + '__call__') as call: + call.return_value = gcdc_agent.Agent() + client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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.name=agent.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_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 = gcdc_agent.UpdateAgentRequest() + + request.agent.name = 'agent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) + await client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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.name=agent.name/value', + ) in kw['metadata'] + + +def test_update_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.update_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_agent( + agent=gcdc_agent.Agent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].agent == gcdc_agent.Agent(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_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.update_agent( + gcdc_agent.UpdateAgentRequest(), + agent=gcdc_agent.Agent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_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.update_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_agent( + agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_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_agent( + gcdc_agent.UpdateAgentRequest(), + agent=gcdc_agent.Agent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__call__') as call: + call.return_value = None + client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_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( + 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_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(), + name='name_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( + 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_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(), + name='name_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_export_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + call.return_value = 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', + 'name=name/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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restore_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + call.return_value = 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', + 'name=name/value', + ) in kw['metadata'] + + +def test_validate_agent(transport: str = 'grpc', request_type=agent.ValidateAgentRequest): + 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.validate_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.AgentValidationResult( + name='name_value', + ) + response = client.validate_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ValidateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.AgentValidationResult) + assert response.name == 'name_value' + + +def test_validate_agent_from_dict(): + test_validate_agent(request_type=dict) + + +def test_validate_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_agent), + '__call__') as call: + client.validate_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ValidateAgentRequest() + + +@pytest.mark.asyncio +async def test_validate_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ValidateAgentRequest): + 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.validate_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult( + name='name_value', + )) + response = await client.validate_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ValidateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.AgentValidationResult) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_validate_agent_async_from_dict(): + await test_validate_agent_async(request_type=dict) + + +def test_validate_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.ValidateAgentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_agent), + '__call__') as call: + call.return_value = agent.AgentValidationResult() + client.validate_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_validate_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.ValidateAgentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) + await client.validate_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_agent_validation_result(transport: str = 'grpc', request_type=agent.GetAgentValidationResultRequest): + 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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.AgentValidationResult( + name='name_value', + ) + response = client.get_agent_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.AgentValidationResult) + assert response.name == 'name_value' + + +def test_get_agent_validation_result_from_dict(): + test_get_agent_validation_result(request_type=dict) + + +def test_get_agent_validation_result_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_validation_result), + '__call__') as call: + client.get_agent_validation_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentValidationResultRequest() + + +@pytest.mark.asyncio +async def test_get_agent_validation_result_async(transport: str = 'grpc_asyncio', request_type=agent.GetAgentValidationResultRequest): + 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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult( + name='name_value', + )) + response = await client.get_agent_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.AgentValidationResult) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_agent_validation_result_async_from_dict(): + await test_get_agent_validation_result_async(request_type=dict) + + +def test_get_agent_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.GetAgentValidationResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent_validation_result), + '__call__') as call: + call.return_value = agent.AgentValidationResult() + client.get_agent_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_agent_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.GetAgentValidationResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent_validation_result), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) + await client.get_agent_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_agent_validation_result_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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.AgentValidationResult() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_agent_validation_result( + name='name_value', + ) + + # Establish that the 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_agent_validation_result_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_validation_result( + agent.GetAgentValidationResultRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_agent_validation_result_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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.AgentValidationResult() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_agent_validation_result( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_agent_validation_result_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_validation_result( + agent.GetAgentValidationResultRequest(), + name='name_value', + ) + + +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.dialogflowcx_v3.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 = ( + 'list_agents', + 'get_agent', + 'create_agent', + 'update_agent', + 'delete_agent', + 'export_agent', + 'restore_agent', + 'validate_agent', + 'get_agent_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.dialogflowcx_v3.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_agents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + 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.dialogflowcx_v3.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" + location = "clam" + agent = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) + actual = AgentsClient.agent_path(project, location, agent) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + } + path = AgentsClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_agent_path(path) + assert expected == actual + +def test_agent_validation_result_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + expected = "projects/{project}/locations/{location}/agents/{agent}/validationResult".format(project=project, location=location, agent=agent, ) + actual = AgentsClient.agent_validation_result_path(project, location, agent) + assert expected == actual + + +def test_parse_agent_validation_result_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "agent": "abalone", + } + path = AgentsClient.agent_validation_result_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_agent_validation_result_path(path) + assert expected == actual + +def test_environment_path(): + project = "squid" + location = "clam" + agent = "whelk" + environment = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + actual = AgentsClient.environment_path(project, location, agent, environment) + assert expected == actual + + +def test_parse_environment_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "environment": "mussel", + } + path = AgentsClient.environment_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_environment_path(path) + assert expected == actual + +def test_flow_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + flow = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = AgentsClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "flow": "octopus", + } + path = AgentsClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_flow_path(path) + assert expected == actual + +def test_flow_validation_result_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + flow = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) + actual = AgentsClient.flow_validation_result_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_validation_result_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "flow": "abalone", + } + path = AgentsClient.flow_validation_result_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_flow_validation_result_path(path) + assert expected == actual + +def test_security_settings_path(): + project = "squid" + location = "clam" + security_settings = "whelk" + expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + actual = AgentsClient.security_settings_path(project, location, security_settings) + assert expected == actual + + +def test_parse_security_settings_path(): + expected = { + "project": "octopus", + "location": "oyster", + "security_settings": "nudibranch", + } + path = AgentsClient.security_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_security_settings_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + 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": "mussel", + } + 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 = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = AgentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + 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 = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AgentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + 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 = "squid" + expected = "projects/{project}".format(project=project, ) + actual = AgentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + 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 = "whelk" + location = "octopus" + 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": "oyster", + "location": "nudibranch", + } + 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/v3/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py new file mode 100644 index 00000000..b143162b --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py @@ -0,0 +1,2418 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.entity_types import EntityTypesAsyncClient +from google.cloud.dialogflowcx_v3.services.entity_types import EntityTypesClient +from google.cloud.dialogflowcx_v3.services.entity_types import pagers +from google.cloud.dialogflowcx_v3.services.entity_types import transports +from google.cloud.dialogflowcx_v3.services.entity_types.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.entity_types.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3.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', + ) + + # Establish that the 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_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', + ) + + +@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', + ) + + # Establish that 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_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', + ) + + +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, + redact=True, + ) + response = client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.GetEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +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, + redact=True, + )) + response = await client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.GetEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +@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', + ) + + # Establish that the 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_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', + ) + + +@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', + ) + + # Establish that 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_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', + ) + + +def test_create_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + redact=True, + ) + response = client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +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] == gcdc_entity_type.CreateEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_create_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + redact=True, + )) + response = await client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_entity_type.EntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_entity_type( + parent='parent_value', + entity_type=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( + gcdc_entity_type.CreateEntityTypeRequest(), + parent='parent_value', + entity_type=gcdc_entity_type.EntityType(name='name_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 = gcdc_entity_type.EntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( + gcdc_entity_type.CreateEntityTypeRequest(), + parent='parent_value', + entity_type=gcdc_entity_type.EntityType(name='name_value'), + ) + + +def test_update_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + redact=True, + ) + response = client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +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] == gcdc_entity_type.UpdateEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_update_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + redact=True, + )) + response = await client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_entity_type.EntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_entity_type( + entity_type=gcdc_entity_type.EntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].entity_type == gcdc_entity_type.EntityType(name='name_value') + assert args[0].update_mask == field_mask_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( + gcdc_entity_type.UpdateEntityTypeRequest(), + entity_type=gcdc_entity_type.EntityType(name='name_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 = gcdc_entity_type.EntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( + gcdc_entity_type.UpdateEntityTypeRequest(), + entity_type=gcdc_entity_type.EntityType(name='name_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_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.dialogflowcx_v3.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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_entity_types_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + 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.dialogflowcx_v3.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_type_path(): + project = "squid" + location = "clam" + agent = "whelk" + entity_type = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + actual = EntityTypesClient.entity_type_path(project, location, agent, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "entity_type": "mussel", + } + 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 = "winkle" + 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": "nautilus", + } + 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 = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = EntityTypesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + 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 = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EntityTypesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + 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 = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = EntityTypesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + 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 = "oyster" + location = "nudibranch" + 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": "cuttlefish", + "location": "mussel", + } + 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/v3/tests/unit/gapic/dialogflowcx_v3/test_environments.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_environments.py new file mode 100644 index 00000000..0010480a --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_environments.py @@ -0,0 +1,2851 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.environments import EnvironmentsAsyncClient +from google.cloud.dialogflowcx_v3.services.environments import EnvironmentsClient +from google.cloud.dialogflowcx_v3.services.environments import pagers +from google.cloud.dialogflowcx_v3.services.environments import transports +from google.cloud.dialogflowcx_v3.services.environments.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.environments.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import environment +from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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(): + 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.dialogflowcx_v3.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', + display_name='display_name_value', + description='description_value', + ) + response = client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +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', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@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_get_environment_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.get_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_environment( + name='name_value', + ) + + # Establish that the 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_environment_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.get_environment( + environment.GetEnvironmentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_environment_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.get_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_environment( + 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_environment_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.get_environment( + environment.GetEnvironmentRequest(), + name='name_value', + ) + + +def test_create_environment(transport: str = 'grpc', request_type=gcdc_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 = operations_pb2.Operation(name='operations/spam') + response = client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +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] == gcdc_environment.CreateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@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 = gcdc_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 = operations_pb2.Operation(name='operations/op') + 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 = gcdc_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(operations_pb2.Operation(name='operations/op')) + 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_create_environment_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.create_environment), + '__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_environment( + parent='parent_value', + environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') + + +def test_create_environment_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.create_environment( + gcdc_environment.CreateEnvironmentRequest(), + parent='parent_value', + environment=gcdc_environment.Environment(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_environment_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.create_environment), + '__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_environment( + parent='parent_value', + environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') + + +@pytest.mark.asyncio +async def test_create_environment_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.create_environment( + gcdc_environment.CreateEnvironmentRequest(), + parent='parent_value', + environment=gcdc_environment.Environment(name='name_value'), + ) + + +def test_update_environment(transport: str = 'grpc', request_type=gcdc_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 = operations_pb2.Operation(name='operations/spam') + response = client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +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] == gcdc_environment.UpdateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@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 = gcdc_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 = operations_pb2.Operation(name='operations/op') + 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 = gcdc_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(operations_pb2.Operation(name='operations/op')) + 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_update_environment_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.update_environment), + '__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_environment( + environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_environment_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.update_environment( + gcdc_environment.UpdateEnvironmentRequest(), + environment=gcdc_environment.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_environment_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.update_environment), + '__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_environment( + environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_environment_flattened_error_async(): + client = EnvironmentsAsyncClient( + credentials=ga_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_environment( + gcdc_environment.UpdateEnvironmentRequest(), + environment=gcdc_environment.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +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_delete_environment_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.delete_environment), + '__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_environment( + 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_environment_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.delete_environment( + environment.DeleteEnvironmentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_environment_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.delete_environment), + '__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_environment( + 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_environment_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.delete_environment( + environment.DeleteEnvironmentRequest(), + name='name_value', + ) + + +def test_lookup_environment_history(transport: str = 'grpc', request_type=environment.LookupEnvironmentHistoryRequest): + 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.lookup_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.LookupEnvironmentHistoryResponse( + next_page_token='next_page_token_value', + ) + response = client.lookup_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.LookupEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.LookupEnvironmentHistoryPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_lookup_environment_history_from_dict(): + test_lookup_environment_history(request_type=dict) + + +def test_lookup_environment_history_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lookup_environment_history), + '__call__') as call: + client.lookup_environment_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.LookupEnvironmentHistoryRequest() + + +@pytest.mark.asyncio +async def test_lookup_environment_history_async(transport: str = 'grpc_asyncio', request_type=environment.LookupEnvironmentHistoryRequest): + 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.lookup_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse( + next_page_token='next_page_token_value', + )) + response = await client.lookup_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.LookupEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.LookupEnvironmentHistoryAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_lookup_environment_history_async_from_dict(): + await test_lookup_environment_history_async(request_type=dict) + + +def test_lookup_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.LookupEnvironmentHistoryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lookup_environment_history), + '__call__') as call: + call.return_value = environment.LookupEnvironmentHistoryResponse() + client.lookup_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_lookup_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.LookupEnvironmentHistoryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lookup_environment_history), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse()) + await client.lookup_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_lookup_environment_history_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.lookup_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.LookupEnvironmentHistoryResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.lookup_environment_history( + name='name_value', + ) + + # Establish that the 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_lookup_environment_history_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.lookup_environment_history( + environment.LookupEnvironmentHistoryRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_lookup_environment_history_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.lookup_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.LookupEnvironmentHistoryResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.lookup_environment_history( + 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_lookup_environment_history_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.lookup_environment_history( + environment.LookupEnvironmentHistoryRequest(), + name='name_value', + ) + + +def test_lookup_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.lookup_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[], + next_page_token='def', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), + ) + pager = client.lookup_environment_history(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_lookup_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.lookup_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[], + next_page_token='def', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + pages = list(client.lookup_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_lookup_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.lookup_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[], + next_page_token='def', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + async_pager = await client.lookup_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.Environment) + for i in responses) + +@pytest.mark.asyncio +async def test_lookup_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.lookup_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[], + next_page_token='def', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.lookup_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.dialogflowcx_v3.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', + 'lookup_environment_history', + ) + 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_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.dialogflowcx_v3.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_environments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (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.dialogflowcx_v3.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_environments_grpc_lro_client(): + client = EnvironmentsClient( + 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_environments_grpc_lro_async_client(): + client = EnvironmentsAsyncClient( + 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_environment_path(): + project = "squid" + location = "clam" + agent = "whelk" + environment = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + actual = EnvironmentsClient.environment_path(project, location, agent, environment) + assert expected == actual + + +def test_parse_environment_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "environment": "mussel", + } + path = EnvironmentsClient.environment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_environment_path(path) + assert expected == actual + +def test_version_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + flow = "abalone" + version = "squid" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + actual = EnvironmentsClient.version_path(project, location, agent, flow, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "clam", + "location": "whelk", + "agent": "octopus", + "flow": "oyster", + "version": "nudibranch", + } + path = EnvironmentsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "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/v3/tests/unit/gapic/dialogflowcx_v3/test_experiments.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_experiments.py new file mode 100644 index 00000000..670fe879 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_experiments.py @@ -0,0 +1,2911 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.experiments import ExperimentsAsyncClient +from google.cloud.dialogflowcx_v3.services.experiments import ExperimentsClient +from google.cloud.dialogflowcx_v3.services.experiments import pagers +from google.cloud.dialogflowcx_v3.services.experiments import transports +from google.cloud.dialogflowcx_v3.services.experiments.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.experiments.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import experiment +from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # 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(): + 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 ExperimentsClient._get_default_mtls_endpoint(None) is None + assert ExperimentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ExperimentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ExperimentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ExperimentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ExperimentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ExperimentsClient, + ExperimentsAsyncClient, +]) +def test_experiments_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", [ + ExperimentsClient, + ExperimentsAsyncClient, +]) +def test_experiments_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_experiments_client_get_transport_class(): + transport = ExperimentsClient.get_transport_class() + available_transports = [ + transports.ExperimentsGrpcTransport, + ] + assert transport in available_transports + + transport = ExperimentsClient.get_transport_class("grpc") + assert transport == transports.ExperimentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient)) +@mock.patch.object(ExperimentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsAsyncClient)) +def test_experiments_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(ExperimentsClient, '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(ExperimentsClient, '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", [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "true"), + (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "false"), + (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient)) +@mock.patch.object(ExperimentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_experiments_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", [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_experiments_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", [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_experiments_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_experiments_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ExperimentsClient( + 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_experiments(transport: str = 'grpc', request_type=experiment.ListExperimentsRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.ListExperimentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExperimentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_experiments_from_dict(): + test_list_experiments(request_type=dict) + + +def test_list_experiments_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=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_experiments), + '__call__') as call: + client.list_experiments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.ListExperimentsRequest() + + +@pytest.mark.asyncio +async def test_list_experiments_async(transport: str = 'grpc_asyncio', request_type=experiment.ListExperimentsRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.ListExperimentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExperimentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_experiments_async_from_dict(): + await test_list_experiments_async(request_type=dict) + + +def test_list_experiments_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.ListExperimentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + call.return_value = experiment.ListExperimentsResponse() + client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_experiments_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.ListExperimentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse()) + await client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_experiments_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_experiments( + parent='parent_value', + ) + + # Establish that the 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_experiments_flattened_error(): + client = ExperimentsClient( + credentials=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_experiments( + experiment.ListExperimentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_experiments_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_experiments( + 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_experiments_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_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_experiments( + experiment.ListExperimentsRequest(), + parent='parent_value', + ) + + +def test_list_experiments_pager(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token='abc', + ), + experiment.ListExperimentsResponse( + experiments=[], + next_page_token='def', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + ], + next_page_token='ghi', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_experiments(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, experiment.Experiment) + for i in results) + +def test_list_experiments_pages(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token='abc', + ), + experiment.ListExperimentsResponse( + experiments=[], + next_page_token='def', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + ], + next_page_token='ghi', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_experiments(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_experiments_async_pager(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token='abc', + ), + experiment.ListExperimentsResponse( + experiments=[], + next_page_token='def', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + ], + next_page_token='ghi', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_experiments(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, experiment.Experiment) + for i in responses) + +@pytest.mark.asyncio +async def test_list_experiments_async_pages(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token='abc', + ), + experiment.ListExperimentsResponse( + experiments=[], + next_page_token='def', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + ], + next_page_token='ghi', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_experiments(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_experiment(transport: str = 'grpc', request_type=experiment.GetExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + ) + response = client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.GetExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +def test_get_experiment_from_dict(): + test_get_experiment(request_type=dict) + + +def test_get_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=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_experiment), + '__call__') as call: + client.get_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.GetExperimentRequest() + + +@pytest.mark.asyncio +async def test_get_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.GetExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + )) + response = await client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.GetExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_get_experiment_async_from_dict(): + await test_get_experiment_async(request_type=dict) + + +def test_get_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.GetExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_experiment), + '__call__') as call: + call.return_value = experiment.Experiment() + client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.GetExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + await client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_experiment( + name='name_value', + ) + + # Establish that the 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_experiment_flattened_error(): + client = ExperimentsClient( + credentials=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_experiment( + experiment.GetExperimentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_experiment( + 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_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_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_experiment( + experiment.GetExperimentRequest(), + name='name_value', + ) + + +def test_create_experiment(transport: str = 'grpc', request_type=gcdc_experiment.CreateExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_experiment.Experiment.State.DRAFT, + ) + response = client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.CreateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +def test_create_experiment_from_dict(): + test_create_experiment(request_type=dict) + + +def test_create_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=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_experiment), + '__call__') as call: + client.create_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.CreateExperimentRequest() + + +@pytest.mark.asyncio +async def test_create_experiment_async(transport: str = 'grpc_asyncio', request_type=gcdc_experiment.CreateExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_experiment.Experiment.State.DRAFT, + )) + response = await client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.CreateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_create_experiment_async_from_dict(): + await test_create_experiment_async(request_type=dict) + + +def test_create_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_experiment.CreateExperimentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), + '__call__') as call: + call.return_value = gcdc_experiment.Experiment() + client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_experiment.CreateExperimentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) + await client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_experiment( + parent='parent_value', + experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') + + +def test_create_experiment_flattened_error(): + client = ExperimentsClient( + credentials=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_experiment( + gcdc_experiment.CreateExperimentRequest(), + parent='parent_value', + experiment=gcdc_experiment.Experiment(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_experiment( + parent='parent_value', + experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') + + +@pytest.mark.asyncio +async def test_create_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_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_experiment( + gcdc_experiment.CreateExperimentRequest(), + parent='parent_value', + experiment=gcdc_experiment.Experiment(name='name_value'), + ) + + +def test_update_experiment(transport: str = 'grpc', request_type=gcdc_experiment.UpdateExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_experiment.Experiment.State.DRAFT, + ) + response = client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.UpdateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +def test_update_experiment_from_dict(): + test_update_experiment(request_type=dict) + + +def test_update_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=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_experiment), + '__call__') as call: + client.update_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.UpdateExperimentRequest() + + +@pytest.mark.asyncio +async def test_update_experiment_async(transport: str = 'grpc_asyncio', request_type=gcdc_experiment.UpdateExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_experiment.Experiment.State.DRAFT, + )) + response = await client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.UpdateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_update_experiment_async_from_dict(): + await test_update_experiment_async(request_type=dict) + + +def test_update_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_experiment.UpdateExperimentRequest() + + request.experiment.name = 'experiment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), + '__call__') as call: + call.return_value = gcdc_experiment.Experiment() + client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'experiment.name=experiment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_experiment.UpdateExperimentRequest() + + request.experiment.name = 'experiment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) + await client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'experiment.name=experiment.name/value', + ) in kw['metadata'] + + +def test_update_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_experiment( + experiment=gcdc_experiment.Experiment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].experiment == gcdc_experiment.Experiment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_experiment_flattened_error(): + client = ExperimentsClient( + credentials=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_experiment( + gcdc_experiment.UpdateExperimentRequest(), + experiment=gcdc_experiment.Experiment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_experiment( + experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_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_experiment( + gcdc_experiment.UpdateExperimentRequest(), + experiment=gcdc_experiment.Experiment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_experiment(transport: str = 'grpc', request_type=experiment.DeleteExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.DeleteExperimentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_experiment_from_dict(): + test_delete_experiment(request_type=dict) + + +def test_delete_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=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_experiment), + '__call__') as call: + client.delete_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.DeleteExperimentRequest() + + +@pytest.mark.asyncio +async def test_delete_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.DeleteExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.DeleteExperimentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_experiment_async_from_dict(): + await test_delete_experiment_async(request_type=dict) + + +def test_delete_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.DeleteExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), + '__call__') as call: + call.return_value = None + client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.DeleteExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), + '__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_experiment( + 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_experiment_flattened_error(): + client = ExperimentsClient( + credentials=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_experiment( + experiment.DeleteExperimentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), + '__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_experiment( + 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_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_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_experiment( + experiment.DeleteExperimentRequest(), + name='name_value', + ) + + +def test_start_experiment(transport: str = 'grpc', request_type=experiment.StartExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + ) + response = client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StartExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +def test_start_experiment_from_dict(): + test_start_experiment(request_type=dict) + + +def test_start_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + client.start_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StartExperimentRequest() + + +@pytest.mark.asyncio +async def test_start_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.StartExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + )) + response = await client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StartExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_start_experiment_async_from_dict(): + await test_start_experiment_async(request_type=dict) + + +def test_start_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.StartExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + call.return_value = experiment.Experiment() + client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.StartExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + await client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_experiment( + name='name_value', + ) + + # Establish that the 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_start_experiment_flattened_error(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_experiment( + experiment.StartExperimentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_start_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_experiment( + 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_start_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_experiment( + experiment.StartExperimentRequest(), + name='name_value', + ) + + +def test_stop_experiment(transport: str = 'grpc', request_type=experiment.StopExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + ) + response = client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StopExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +def test_stop_experiment_from_dict(): + test_stop_experiment(request_type=dict) + + +def test_stop_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + client.stop_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StopExperimentRequest() + + +@pytest.mark.asyncio +async def test_stop_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.StopExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + )) + response = await client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StopExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_stop_experiment_async_from_dict(): + await test_stop_experiment_async(request_type=dict) + + +def test_stop_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.StopExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + call.return_value = experiment.Experiment() + client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.StopExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + await client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.stop_experiment( + name='name_value', + ) + + # Establish that the 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_stop_experiment_flattened_error(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_experiment( + experiment.StopExperimentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_stop_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.stop_experiment( + 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_stop_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_experiment( + experiment.StopExperimentRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ExperimentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ExperimentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ExperimentsGrpcTransport, + transports.ExperimentsGrpcAsyncIOTransport, +]) +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 = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ExperimentsGrpcTransport, + ) + +def test_experiments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ExperimentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_experiments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ExperimentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_experiments', + 'get_experiment', + 'create_experiment', + 'update_experiment', + 'delete_experiment', + 'start_experiment', + 'stop_experiment', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_experiments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExperimentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_experiments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExperimentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_experiments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExperimentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_experiments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ExperimentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_experiments_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ExperimentsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ExperimentsGrpcTransport, + transports.ExperimentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_experiments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ExperimentsGrpcTransport, + transports.ExperimentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_experiments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_experiments_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_experiments_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_experiments_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) +def test_experiments_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = 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_experiments_host_no_port(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_experiments_host_with_port(): + client = ExperimentsClient( + 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_experiments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ExperimentsGrpcTransport( + 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_experiments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ExperimentsGrpcAsyncIOTransport( + 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.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) +def test_experiments_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.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) +def test_experiments_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_experiment_path(): + project = "squid" + location = "clam" + agent = "whelk" + environment = "octopus" + experiment = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format(project=project, location=location, agent=agent, environment=environment, experiment=experiment, ) + actual = ExperimentsClient.experiment_path(project, location, agent, environment, experiment) + assert expected == actual + + +def test_parse_experiment_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "environment": "winkle", + "experiment": "nautilus", + } + path = ExperimentsClient.experiment_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_experiment_path(path) + assert expected == actual + +def test_version_path(): + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" + version = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + actual = ExperimentsClient.version_path(project, location, agent, flow, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "version": "mussel", + } + path = ExperimentsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ExperimentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ExperimentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = ExperimentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ExperimentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ExperimentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ExperimentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = ExperimentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ExperimentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.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 = ExperimentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ExperimentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.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.ExperimentsTransport, '_prep_wrapped_messages') as prep: + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ExperimentsTransport, '_prep_wrapped_messages') as prep: + transport_class = ExperimentsClient.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/v3/tests/unit/gapic/dialogflowcx_v3/test_flows.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_flows.py new file mode 100644 index 00000000..3ad96e96 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_flows.py @@ -0,0 +1,3472 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.flows import FlowsAsyncClient +from google.cloud.dialogflowcx_v3.services.flows import FlowsClient +from google.cloud.dialogflowcx_v3.services.flows import pagers +from google.cloud.dialogflowcx_v3.services.flows import transports +from google.cloud.dialogflowcx_v3.services.flows.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.flows.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow +from google.cloud.dialogflowcx_v3.types import fulfillment +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import response_message +from google.cloud.dialogflowcx_v3.types import validation_message +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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(): + 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 FlowsClient._get_default_mtls_endpoint(None) is None + assert FlowsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FlowsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FlowsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FlowsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FlowsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + FlowsClient, + FlowsAsyncClient, +]) +def test_flows_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", [ + FlowsClient, + FlowsAsyncClient, +]) +def test_flows_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_flows_client_get_transport_class(): + transport = FlowsClient.get_transport_class() + available_transports = [ + transports.FlowsGrpcTransport, + ] + assert transport in available_transports + + transport = FlowsClient.get_transport_class("grpc") + assert transport == transports.FlowsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FlowsClient, transports.FlowsGrpcTransport, "grpc"), + (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(FlowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsClient)) +@mock.patch.object(FlowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsAsyncClient)) +def test_flows_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(FlowsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=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(FlowsClient, '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", [ + (FlowsClient, transports.FlowsGrpcTransport, "grpc", "true"), + (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FlowsClient, transports.FlowsGrpcTransport, "grpc", "false"), + (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(FlowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsClient)) +@mock.patch.object(FlowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_flows_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", [ + (FlowsClient, transports.FlowsGrpcTransport, "grpc"), + (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_flows_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", [ + (FlowsClient, transports.FlowsGrpcTransport, "grpc"), + (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_flows_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_flows_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3.services.flows.transports.FlowsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FlowsClient( + 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_flow(transport: str = 'grpc', request_type=gcdc_flow.CreateFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.create_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.CreateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_create_flow_from_dict(): + test_create_flow(request_type=dict) + + +def test_create_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow), + '__call__') as call: + client.create_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.CreateFlowRequest() + + +@pytest.mark.asyncio +async def test_create_flow_async(transport: str = 'grpc_asyncio', request_type=gcdc_flow.CreateFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.create_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.CreateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_create_flow_async_from_dict(): + await test_create_flow_async(request_type=dict) + + +def test_create_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_flow.CreateFlowRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + call.return_value = gcdc_flow.Flow() + client.create_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_flow.CreateFlowRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) + await client.create_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_flow_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_flow( + parent='parent_value', + flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') + + +def test_create_flow_flattened_error(): + client = FlowsClient( + credentials=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_flow( + gcdc_flow.CreateFlowRequest(), + parent='parent_value', + flow=gcdc_flow.Flow(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_flow_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_flow( + parent='parent_value', + flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') + + +@pytest.mark.asyncio +async def test_create_flow_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow( + gcdc_flow.CreateFlowRequest(), + parent='parent_value', + flow=gcdc_flow.Flow(name='name_value'), + ) + + +def test_delete_flow(transport: str = 'grpc', request_type=flow.DeleteFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.DeleteFlowRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_flow_from_dict(): + test_delete_flow(request_type=dict) + + +def test_delete_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow), + '__call__') as call: + client.delete_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.DeleteFlowRequest() + + +@pytest.mark.asyncio +async def test_delete_flow_async(transport: str = 'grpc_asyncio', request_type=flow.DeleteFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.DeleteFlowRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_flow_async_from_dict(): + await test_delete_flow_async(request_type=dict) + + +def test_delete_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.DeleteFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + call.return_value = None + client.delete_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.DeleteFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_flow( + name='name_value', + ) + + # Establish that the 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_flow_flattened_error(): + client = FlowsClient( + credentials=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_flow( + flow.DeleteFlowRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_flow_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + # 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_flow( + 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_flow_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow( + flow.DeleteFlowRequest(), + name='name_value', + ) + + +def test_list_flows(transport: str = 'grpc', request_type=flow.ListFlowsRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.ListFlowsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_flows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ListFlowsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFlowsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_flows_from_dict(): + test_list_flows(request_type=dict) + + +def test_list_flows_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flows), + '__call__') as call: + client.list_flows() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ListFlowsRequest() + + +@pytest.mark.asyncio +async def test_list_flows_async(transport: str = 'grpc_asyncio', request_type=flow.ListFlowsRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_flows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ListFlowsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFlowsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_flows_async_from_dict(): + await test_list_flows_async(request_type=dict) + + +def test_list_flows_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ListFlowsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + call.return_value = flow.ListFlowsResponse() + client.list_flows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_flows_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ListFlowsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse()) + await client.list_flows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_flows_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.ListFlowsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_flows( + parent='parent_value', + ) + + # Establish that the 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_flows_flattened_error(): + client = FlowsClient( + credentials=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_flows( + flow.ListFlowsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_flows_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.ListFlowsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_flows( + 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_flows_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flows( + flow.ListFlowsRequest(), + parent='parent_value', + ) + + +def test_list_flows_pager(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + flow.Flow(), + ], + next_page_token='abc', + ), + flow.ListFlowsResponse( + flows=[], + next_page_token='def', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + ], + next_page_token='ghi', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_flows(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, flow.Flow) + for i in results) + +def test_list_flows_pages(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + flow.Flow(), + ], + next_page_token='abc', + ), + flow.ListFlowsResponse( + flows=[], + next_page_token='def', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + ], + next_page_token='ghi', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + ], + ), + RuntimeError, + ) + pages = list(client.list_flows(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_flows_async_pager(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + flow.Flow(), + ], + next_page_token='abc', + ), + flow.ListFlowsResponse( + flows=[], + next_page_token='def', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + ], + next_page_token='ghi', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_flows(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, flow.Flow) + for i in responses) + +@pytest.mark.asyncio +async def test_list_flows_async_pages(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + flow.Flow(), + ], + next_page_token='abc', + ), + flow.ListFlowsResponse( + flows=[], + next_page_token='def', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + ], + next_page_token='ghi', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_flows(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_flow(transport: str = 'grpc', request_type=flow.GetFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.get_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_get_flow_from_dict(): + test_get_flow(request_type=dict) + + +def test_get_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow), + '__call__') as call: + client.get_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowRequest() + + +@pytest.mark.asyncio +async def test_get_flow_async(transport: str = 'grpc_asyncio', request_type=flow.GetFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.get_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_get_flow_async_from_dict(): + await test_get_flow_async(request_type=dict) + + +def test_get_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.GetFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + call.return_value = flow.Flow() + client.get_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.GetFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow()) + await client.get_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.Flow() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_flow( + name='name_value', + ) + + # Establish that the 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_flow_flattened_error(): + client = FlowsClient( + credentials=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_flow( + flow.GetFlowRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_flow_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.Flow() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_flow( + 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_flow_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow( + flow.GetFlowRequest(), + name='name_value', + ) + + +def test_update_flow(transport: str = 'grpc', request_type=gcdc_flow.UpdateFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.update_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.UpdateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_update_flow_from_dict(): + test_update_flow(request_type=dict) + + +def test_update_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow), + '__call__') as call: + client.update_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.UpdateFlowRequest() + + +@pytest.mark.asyncio +async def test_update_flow_async(transport: str = 'grpc_asyncio', request_type=gcdc_flow.UpdateFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.update_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.UpdateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_update_flow_async_from_dict(): + await test_update_flow_async(request_type=dict) + + +def test_update_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_flow.UpdateFlowRequest() + + request.flow.name = 'flow.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + call.return_value = gcdc_flow.Flow() + client.update_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'flow.name=flow.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_flow.UpdateFlowRequest() + + request.flow.name = 'flow.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) + await client.update_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'flow.name=flow.name/value', + ) in kw['metadata'] + + +def test_update_flow_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_flow( + flow=gcdc_flow.Flow(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].flow == gcdc_flow.Flow(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_flow_flattened_error(): + client = FlowsClient( + credentials=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_flow( + gcdc_flow.UpdateFlowRequest(), + flow=gcdc_flow.Flow(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_flow_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_flow( + flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_flow_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow( + gcdc_flow.UpdateFlowRequest(), + flow=gcdc_flow.Flow(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_train_flow(transport: str = 'grpc', request_type=flow.TrainFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.train_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.TrainFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_train_flow_from_dict(): + test_train_flow(request_type=dict) + + +def test_train_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow), + '__call__') as call: + client.train_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.TrainFlowRequest() + + +@pytest.mark.asyncio +async def test_train_flow_async(transport: str = 'grpc_asyncio', request_type=flow.TrainFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.train_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.TrainFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_train_flow_async_from_dict(): + await test_train_flow_async(request_type=dict) + + +def test_train_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.TrainFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.train_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_train_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.TrainFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.train_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_train_flow_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.train_flow( + name='name_value', + ) + + # Establish that the 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_train_flow_flattened_error(): + client = FlowsClient( + credentials=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_flow( + flow.TrainFlowRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_train_flow_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + # 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_flow( + 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_train_flow_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow( + flow.TrainFlowRequest(), + name='name_value', + ) + + +def test_validate_flow(transport: str = 'grpc', request_type=flow.ValidateFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.FlowValidationResult( + name='name_value', + ) + response = client.validate_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ValidateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.FlowValidationResult) + assert response.name == 'name_value' + + +def test_validate_flow_from_dict(): + test_validate_flow(request_type=dict) + + +def test_validate_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_flow), + '__call__') as call: + client.validate_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ValidateFlowRequest() + + +@pytest.mark.asyncio +async def test_validate_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ValidateFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult( + name='name_value', + )) + response = await client.validate_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ValidateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.FlowValidationResult) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_validate_flow_async_from_dict(): + await test_validate_flow_async(request_type=dict) + + +def test_validate_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ValidateFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_flow), + '__call__') as call: + call.return_value = flow.FlowValidationResult() + client.validate_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_validate_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ValidateFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) + await client.validate_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_validation_result(transport: str = 'grpc', request_type=flow.GetFlowValidationResultRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.FlowValidationResult( + name='name_value', + ) + response = client.get_flow_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.FlowValidationResult) + assert response.name == 'name_value' + + +def test_get_flow_validation_result_from_dict(): + test_get_flow_validation_result(request_type=dict) + + +def test_get_flow_validation_result_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow_validation_result), + '__call__') as call: + client.get_flow_validation_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowValidationResultRequest() + + +@pytest.mark.asyncio +async def test_get_flow_validation_result_async(transport: str = 'grpc_asyncio', request_type=flow.GetFlowValidationResultRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult( + name='name_value', + )) + response = await client.get_flow_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.FlowValidationResult) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_flow_validation_result_async_from_dict(): + await test_get_flow_validation_result_async(request_type=dict) + + +def test_get_flow_validation_result_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.GetFlowValidationResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + call.return_value = flow.FlowValidationResult() + client.get_flow_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_validation_result_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.GetFlowValidationResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) + await client.get_flow_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_validation_result_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.FlowValidationResult() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_flow_validation_result( + name='name_value', + ) + + # Establish that the 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_flow_validation_result_flattened_error(): + client = FlowsClient( + credentials=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_flow_validation_result( + flow.GetFlowValidationResultRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_flow_validation_result_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.FlowValidationResult() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_flow_validation_result( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_flow_validation_result_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow_validation_result( + flow.GetFlowValidationResultRequest(), + name='name_value', + ) + + +def test_import_flow(transport: str = 'grpc', request_type=flow.ImportFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_flow_from_dict(): + test_import_flow(request_type=dict) + + +def test_import_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_flow), + '__call__') as call: + client.import_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + +@pytest.mark.asyncio +async def test_import_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ImportFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_flow_async_from_dict(): + await test_import_flow_async(request_type=dict) + + +def test_import_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ImportFlowRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_flow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ImportFlowRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_export_flow(transport: str = 'grpc', request_type=flow.ExportFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_flow_from_dict(): + test_export_flow(request_type=dict) + + +def test_export_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_flow), + '__call__') as call: + client.export_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + +@pytest.mark.asyncio +async def test_export_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ExportFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_flow_async_from_dict(): + await test_export_flow_async(request_type=dict) + + +def test_export_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ExportFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_flow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_export_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ExportFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FlowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FlowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FlowsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FlowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FlowsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FlowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FlowsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FlowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FlowsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FlowsGrpcTransport, + transports.FlowsGrpcAsyncIOTransport, +]) +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 = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FlowsGrpcTransport, + ) + +def test_flows_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FlowsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_flows_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3.services.flows.transports.FlowsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FlowsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_flow', + 'delete_flow', + 'list_flows', + 'get_flow', + 'update_flow', + 'train_flow', + 'validate_flow', + 'get_flow_validation_result', + 'import_flow', + 'export_flow', + ) + 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_flows_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FlowsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_flows_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FlowsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_flows_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FlowsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_flows_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FlowsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_flows_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FlowsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FlowsGrpcTransport, + transports.FlowsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_flows_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FlowsGrpcTransport, + transports.FlowsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_flows_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_flows_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_flows_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_flows_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) +def test_flows_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = 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_flows_host_no_port(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_flows_host_with_port(): + client = FlowsClient( + 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_flows_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FlowsGrpcTransport( + 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_flows_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FlowsGrpcAsyncIOTransport( + 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.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) +def test_flows_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.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) +def test_flows_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_flows_grpc_lro_client(): + client = FlowsClient( + 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_flows_grpc_lro_async_client(): + client = FlowsAsyncClient( + 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_flow_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = FlowsClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "flow": "mussel", + } + path = FlowsClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_flow_path(path) + assert expected == actual + +def test_flow_validation_result_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + flow = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) + actual = FlowsClient.flow_validation_result_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_validation_result_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "flow": "octopus", + } + path = FlowsClient.flow_validation_result_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_flow_validation_result_path(path) + assert expected == actual + +def test_intent_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + intent = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = FlowsClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "intent": "abalone", + } + path = FlowsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_intent_path(path) + assert expected == actual + +def test_page_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + page = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + actual = FlowsClient.page_path(project, location, agent, flow, page) + assert expected == actual + + +def test_parse_page_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "flow": "winkle", + "page": "nautilus", + } + path = FlowsClient.page_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_page_path(path) + assert expected == actual + +def test_transition_route_group_path(): + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" + transition_route_group = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + actual = FlowsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) + assert expected == actual + + +def test_parse_transition_route_group_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "transition_route_group": "mussel", + } + path = FlowsClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_transition_route_group_path(path) + assert expected == actual + +def test_webhook_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = FlowsClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", + } + path = FlowsClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FlowsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = FlowsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = FlowsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = FlowsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FlowsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = FlowsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = FlowsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = FlowsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.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 = FlowsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = FlowsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.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.FlowsTransport, '_prep_wrapped_messages') as prep: + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FlowsTransport, '_prep_wrapped_messages') as prep: + transport_class = FlowsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_intents.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_intents.py new file mode 100644 index 00000000..30ee2672 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_intents.py @@ -0,0 +1,2429 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.intents import IntentsAsyncClient +from google.cloud.dialogflowcx_v3.services.intents import IntentsClient +from google.cloud.dialogflowcx_v3.services.intents import pagers +from google.cloud.dialogflowcx_v3.services.intents import transports +from google.cloud.dialogflowcx_v3.services.intents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.intents.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3.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', + ) + + # Establish that the 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_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', + ) + + +@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', + ) + + # Establish that 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_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', + ) + + +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', + priority=898, + is_fallback=True, + description='description_value', + ) + response = client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.GetIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +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', + priority=898, + is_fallback=True, + description='description_value', + )) + response = await client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.GetIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +@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', + ) + + # Establish that the 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_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', + ) + + +@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', + ) + + # Establish that 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_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', + ) + + +def test_create_intent(transport: str = 'grpc', request_type=gcdc_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 = gcdc_intent.Intent( + name='name_value', + display_name='display_name_value', + priority=898, + is_fallback=True, + description='description_value', + ) + response = client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_intent.CreateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +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] == gcdc_intent.CreateIntentRequest() + + +@pytest.mark.asyncio +async def test_create_intent_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_intent.Intent( + name='name_value', + display_name='display_name_value', + priority=898, + is_fallback=True, + description='description_value', + )) + response = await client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_intent.CreateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +@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 = gcdc_intent.CreateIntentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + call.return_value = gcdc_intent.Intent() + client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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 = gcdc_intent.CreateIntentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) + await client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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 = gcdc_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=gcdc_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 == gcdc_intent.Intent(name='name_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( + gcdc_intent.CreateIntentRequest(), + parent='parent_value', + intent=gcdc_intent.Intent(name='name_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 = gcdc_intent.Intent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_intent.Intent(name='name_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( + gcdc_intent.CreateIntentRequest(), + parent='parent_value', + intent=gcdc_intent.Intent(name='name_value'), + ) + + +def test_update_intent(transport: str = 'grpc', request_type=gcdc_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 = gcdc_intent.Intent( + name='name_value', + display_name='display_name_value', + priority=898, + is_fallback=True, + description='description_value', + ) + response = client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_intent.UpdateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +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] == gcdc_intent.UpdateIntentRequest() + + +@pytest.mark.asyncio +async def test_update_intent_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_intent.Intent( + name='name_value', + display_name='display_name_value', + priority=898, + is_fallback=True, + description='description_value', + )) + response = await client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_intent.UpdateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +@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 = gcdc_intent.UpdateIntentRequest() + + request.intent.name = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = gcdc_intent.Intent() + client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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 = gcdc_intent.UpdateIntentRequest() + + request.intent.name = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) + await client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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 = gcdc_intent.Intent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_intent( + intent=gcdc_intent.Intent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].intent == gcdc_intent.Intent(name='name_value') + assert args[0].update_mask == field_mask_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( + gcdc_intent.UpdateIntentRequest(), + intent=gcdc_intent.Intent(name='name_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 = gcdc_intent.Intent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_intent.Intent(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].intent == gcdc_intent.Intent(name='name_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( + gcdc_intent.UpdateIntentRequest(), + intent=gcdc_intent.Intent(name='name_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_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.dialogflowcx_v3.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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_intents_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_intents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + 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.dialogflowcx_v3.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_entity_type_path(): + project = "squid" + location = "clam" + agent = "whelk" + entity_type = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + actual = IntentsClient.entity_type_path(project, location, agent, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "entity_type": "mussel", + } + path = IntentsClient.entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_entity_type_path(path) + assert expected == actual + +def test_intent_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + intent = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = IntentsClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "intent": "octopus", + } + 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 = "oyster" + 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": "nudibranch", + } + 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 = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = IntentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + 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 = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = IntentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + 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 = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = IntentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + 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 = "squid" + location = "clam" + 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": "whelk", + "location": "octopus", + } + 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/v3/tests/unit/gapic/dialogflowcx_v3/test_pages.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_pages.py new file mode 100644 index 00000000..fa67219f --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_pages.py @@ -0,0 +1,2504 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.pages import PagesAsyncClient +from google.cloud.dialogflowcx_v3.services.pages import PagesClient +from google.cloud.dialogflowcx_v3.services.pages import pagers +from google.cloud.dialogflowcx_v3.services.pages import transports +from google.cloud.dialogflowcx_v3.services.pages.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.pages.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import fulfillment +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import page as gcdc_page +from google.cloud.dialogflowcx_v3.types import response_message +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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 PagesClient._get_default_mtls_endpoint(None) is None + assert PagesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PagesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PagesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PagesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PagesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + PagesClient, + PagesAsyncClient, +]) +def test_pages_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", [ + PagesClient, + PagesAsyncClient, +]) +def test_pages_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_pages_client_get_transport_class(): + transport = PagesClient.get_transport_class() + available_transports = [ + transports.PagesGrpcTransport, + ] + assert transport in available_transports + + transport = PagesClient.get_transport_class("grpc") + assert transport == transports.PagesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PagesClient, transports.PagesGrpcTransport, "grpc"), + (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PagesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesClient)) +@mock.patch.object(PagesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesAsyncClient)) +def test_pages_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(PagesClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=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(PagesClient, '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", [ + (PagesClient, transports.PagesGrpcTransport, "grpc", "true"), + (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PagesClient, transports.PagesGrpcTransport, "grpc", "false"), + (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PagesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesClient)) +@mock.patch.object(PagesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_pages_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", [ + (PagesClient, transports.PagesGrpcTransport, "grpc"), + (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_pages_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", [ + (PagesClient, transports.PagesGrpcTransport, "grpc"), + (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_pages_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_pages_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3.services.pages.transports.PagesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PagesClient( + 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_pages(transport: str = 'grpc', request_type=page.ListPagesRequest): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_pages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.ListPagesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_pages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == page.ListPagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPagesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_pages_from_dict(): + test_list_pages(request_type=dict) + + +def test_list_pages_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PagesClient( + credentials=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_pages), + '__call__') as call: + client.list_pages() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == page.ListPagesRequest() + + +@pytest.mark.asyncio +async def test_list_pages_async(transport: str = 'grpc_asyncio', request_type=page.ListPagesRequest): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_pages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_pages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == page.ListPagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPagesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_pages_async_from_dict(): + await test_list_pages_async(request_type=dict) + + +def test_list_pages_field_headers(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.ListPagesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + call.return_value = page.ListPagesResponse() + client.list_pages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_pages_field_headers_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.ListPagesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse()) + await client.list_pages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_pages_flattened(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.ListPagesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_pages( + parent='parent_value', + ) + + # Establish that the 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_pages_flattened_error(): + client = PagesClient( + credentials=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_pages( + page.ListPagesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_pages_flattened_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.ListPagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_pages( + 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_pages_flattened_error_async(): + client = PagesAsyncClient( + credentials=ga_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_pages( + page.ListPagesRequest(), + parent='parent_value', + ) + + +def test_list_pages_pager(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + page.Page(), + ], + next_page_token='abc', + ), + page.ListPagesResponse( + pages=[], + next_page_token='def', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + ], + next_page_token='ghi', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_pages(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, page.Page) + for i in results) + +def test_list_pages_pages(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + page.Page(), + ], + next_page_token='abc', + ), + page.ListPagesResponse( + pages=[], + next_page_token='def', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + ], + next_page_token='ghi', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + ], + ), + RuntimeError, + ) + pages = list(client.list_pages(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_pages_async_pager(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + page.Page(), + ], + next_page_token='abc', + ), + page.ListPagesResponse( + pages=[], + next_page_token='def', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + ], + next_page_token='ghi', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_pages(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, page.Page) + for i in responses) + +@pytest.mark.asyncio +async def test_list_pages_async_pages(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + page.Page(), + ], + next_page_token='abc', + ), + page.ListPagesResponse( + pages=[], + next_page_token='def', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + ], + next_page_token='ghi', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_pages(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_page(transport: str = 'grpc', request_type=page.GetPageRequest): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.get_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == page.GetPageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_get_page_from_dict(): + test_get_page(request_type=dict) + + +def test_get_page_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PagesClient( + credentials=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_page), + '__call__') as call: + client.get_page() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == page.GetPageRequest() + + +@pytest.mark.asyncio +async def test_get_page_async(transport: str = 'grpc_asyncio', request_type=page.GetPageRequest): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.get_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == page.GetPageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_get_page_async_from_dict(): + await test_get_page_async(request_type=dict) + + +def test_get_page_field_headers(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.GetPageRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_page), + '__call__') as call: + call.return_value = page.Page() + client.get_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_page_field_headers_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.GetPageRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_page), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.Page()) + await client.get_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_page_flattened(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.Page() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_page( + name='name_value', + ) + + # Establish that the 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_page_flattened_error(): + client = PagesClient( + credentials=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_page( + page.GetPageRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_page_flattened_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.Page() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.Page()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_page( + 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_page_flattened_error_async(): + client = PagesAsyncClient( + credentials=ga_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_page( + page.GetPageRequest(), + name='name_value', + ) + + +def test_create_page(transport: str = 'grpc', request_type=gcdc_page.CreatePageRequest): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.create_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.CreatePageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_create_page_from_dict(): + test_create_page(request_type=dict) + + +def test_create_page_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PagesClient( + credentials=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_page), + '__call__') as call: + client.create_page() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.CreatePageRequest() + + +@pytest.mark.asyncio +async def test_create_page_async(transport: str = 'grpc_asyncio', request_type=gcdc_page.CreatePageRequest): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.create_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.CreatePageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_create_page_async_from_dict(): + await test_create_page_async(request_type=dict) + + +def test_create_page_field_headers(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_page.CreatePageRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_page), + '__call__') as call: + call.return_value = gcdc_page.Page() + client.create_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_page_field_headers_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_page.CreatePageRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_page), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) + await client.create_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_page_flattened(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_page( + parent='parent_value', + page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') + + +def test_create_page_flattened_error(): + client = PagesClient( + credentials=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_page( + gcdc_page.CreatePageRequest(), + parent='parent_value', + page=gcdc_page.Page(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_page_flattened_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_page( + parent='parent_value', + page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') + + +@pytest.mark.asyncio +async def test_create_page_flattened_error_async(): + client = PagesAsyncClient( + credentials=ga_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_page( + gcdc_page.CreatePageRequest(), + parent='parent_value', + page=gcdc_page.Page(name='name_value'), + ) + + +def test_update_page(transport: str = 'grpc', request_type=gcdc_page.UpdatePageRequest): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.update_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.UpdatePageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_update_page_from_dict(): + test_update_page(request_type=dict) + + +def test_update_page_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PagesClient( + credentials=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_page), + '__call__') as call: + client.update_page() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.UpdatePageRequest() + + +@pytest.mark.asyncio +async def test_update_page_async(transport: str = 'grpc_asyncio', request_type=gcdc_page.UpdatePageRequest): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.update_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.UpdatePageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_update_page_async_from_dict(): + await test_update_page_async(request_type=dict) + + +def test_update_page_field_headers(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_page.UpdatePageRequest() + + request.page.name = 'page.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_page), + '__call__') as call: + call.return_value = gcdc_page.Page() + client.update_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'page.name=page.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_page_field_headers_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_page.UpdatePageRequest() + + request.page.name = 'page.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_page), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) + await client.update_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'page.name=page.name/value', + ) in kw['metadata'] + + +def test_update_page_flattened(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_page( + page=gcdc_page.Page(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].page == gcdc_page.Page(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_page_flattened_error(): + client = PagesClient( + credentials=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_page( + gcdc_page.UpdatePageRequest(), + page=gcdc_page.Page(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_page_flattened_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_page( + page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_page_flattened_error_async(): + client = PagesAsyncClient( + credentials=ga_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_page( + gcdc_page.UpdatePageRequest(), + page=gcdc_page.Page(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_page(transport: str = 'grpc', request_type=page.DeletePageRequest): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == page.DeletePageRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_page_from_dict(): + test_delete_page(request_type=dict) + + +def test_delete_page_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PagesClient( + credentials=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_page), + '__call__') as call: + client.delete_page() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == page.DeletePageRequest() + + +@pytest.mark.asyncio +async def test_delete_page_async(transport: str = 'grpc_asyncio', request_type=page.DeletePageRequest): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == page.DeletePageRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_page_async_from_dict(): + await test_delete_page_async(request_type=dict) + + +def test_delete_page_field_headers(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.DeletePageRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_page), + '__call__') as call: + call.return_value = None + client.delete_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_page_field_headers_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.DeletePageRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_page), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_page_flattened(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_page( + name='name_value', + ) + + # Establish that the 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_page_flattened_error(): + client = PagesClient( + credentials=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_page( + page.DeletePageRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_page_flattened_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_page), + '__call__') as call: + # 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_page( + 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_page_flattened_error_async(): + client = PagesAsyncClient( + credentials=ga_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_page( + page.DeletePageRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PagesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PagesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PagesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PagesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PagesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PagesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PagesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PagesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PagesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PagesGrpcTransport, + transports.PagesGrpcAsyncIOTransport, +]) +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 = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PagesGrpcTransport, + ) + +def test_pages_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PagesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_pages_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3.services.pages.transports.PagesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PagesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_pages', + 'get_page', + 'create_page', + 'update_page', + 'delete_page', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_pages_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PagesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_pages_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PagesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_pages_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PagesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_pages_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + PagesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_pages_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + PagesClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PagesGrpcTransport, + transports.PagesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_pages_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PagesGrpcTransport, + transports.PagesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_pages_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_pages_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_pages_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_pages_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) +def test_pages_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = 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_pages_host_no_port(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_pages_host_with_port(): + client = PagesClient( + 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_pages_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PagesGrpcTransport( + 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_pages_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PagesGrpcAsyncIOTransport( + 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.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) +def test_pages_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.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) +def test_pages_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_type_path(): + project = "squid" + location = "clam" + agent = "whelk" + entity_type = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + actual = PagesClient.entity_type_path(project, location, agent, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "entity_type": "mussel", + } + path = PagesClient.entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_entity_type_path(path) + assert expected == actual + +def test_flow_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + flow = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = PagesClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "flow": "octopus", + } + path = PagesClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_flow_path(path) + assert expected == actual + +def test_intent_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + intent = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = PagesClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "intent": "abalone", + } + path = PagesClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_intent_path(path) + assert expected == actual + +def test_page_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + page = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + actual = PagesClient.page_path(project, location, agent, flow, page) + assert expected == actual + + +def test_parse_page_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "flow": "winkle", + "page": "nautilus", + } + path = PagesClient.page_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_page_path(path) + assert expected == actual + +def test_transition_route_group_path(): + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" + transition_route_group = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + actual = PagesClient.transition_route_group_path(project, location, agent, flow, transition_route_group) + assert expected == actual + + +def test_parse_transition_route_group_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "transition_route_group": "mussel", + } + path = PagesClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_transition_route_group_path(path) + assert expected == actual + +def test_webhook_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = PagesClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", + } + path = PagesClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PagesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = PagesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = PagesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = PagesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PagesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = PagesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = PagesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = PagesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.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 = PagesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = PagesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.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.PagesTransport, '_prep_wrapped_messages') as prep: + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PagesTransport, '_prep_wrapped_messages') as prep: + transport_class = PagesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py new file mode 100644 index 00000000..99f04405 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py @@ -0,0 +1,2419 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.security_settings_service import SecuritySettingsServiceAsyncClient +from google.cloud.dialogflowcx_v3.services.security_settings_service import SecuritySettingsServiceClient +from google.cloud.dialogflowcx_v3.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3.services.security_settings_service import transports +from google.cloud.dialogflowcx_v3.services.security_settings_service.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.security_settings_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import security_settings +from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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 SecuritySettingsServiceClient._get_default_mtls_endpoint(None) is None + assert SecuritySettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecuritySettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecuritySettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecuritySettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecuritySettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SecuritySettingsServiceClient, + SecuritySettingsServiceAsyncClient, +]) +def test_security_settings_service_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", [ + SecuritySettingsServiceClient, + SecuritySettingsServiceAsyncClient, +]) +def test_security_settings_service_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_security_settings_service_client_get_transport_class(): + transport = SecuritySettingsServiceClient.get_transport_class() + available_transports = [ + transports.SecuritySettingsServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SecuritySettingsServiceClient.get_transport_class("grpc") + assert transport == transports.SecuritySettingsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), + (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SecuritySettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceClient)) +@mock.patch.object(SecuritySettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceAsyncClient)) +def test_security_settings_service_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(SecuritySettingsServiceClient, '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(SecuritySettingsServiceClient, '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", [ + (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc", "true"), + (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc", "false"), + (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SecuritySettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceClient)) +@mock.patch.object(SecuritySettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_settings_service_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", [ + (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), + (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_settings_service_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", [ + (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), + (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_settings_service_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_security_settings_service_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecuritySettingsServiceClient( + 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_security_settings(transport: str = 'grpc', request_type=gcdc_security_settings.CreateSecuritySettingsRequest): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + retention_window_days=2271, + ) + response = client.create_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +def test_create_security_settings_from_dict(): + test_create_security_settings(request_type=dict) + + +def test_create_security_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecuritySettingsServiceClient( + credentials=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_security_settings), + '__call__') as call: + client.create_security_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() + + +@pytest.mark.asyncio +async def test_create_security_settings_async(transport: str = 'grpc_asyncio', request_type=gcdc_security_settings.CreateSecuritySettingsRequest): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + )) + response = await client.create_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +@pytest.mark.asyncio +async def test_create_security_settings_async_from_dict(): + await test_create_security_settings_async(request_type=dict) + + +def test_create_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_security_settings.CreateSecuritySettingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), + '__call__') as call: + call.return_value = gcdc_security_settings.SecuritySettings() + client.create_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_security_settings.CreateSecuritySettingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) + await client.create_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_security_settings( + parent='parent_value', + security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') + + +def test_create_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=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_security_settings( + gcdc_security_settings.CreateSecuritySettingsRequest(), + parent='parent_value', + security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_security_settings( + parent='parent_value', + security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') + + +@pytest.mark.asyncio +async def test_create_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_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_security_settings( + gcdc_security_settings.CreateSecuritySettingsRequest(), + parent='parent_value', + security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), + ) + + +def test_get_security_settings(transport: str = 'grpc', request_type=security_settings.GetSecuritySettingsRequest): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + retention_window_days=2271, + ) + response = client.get_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.GetSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +def test_get_security_settings_from_dict(): + test_get_security_settings(request_type=dict) + + +def test_get_security_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecuritySettingsServiceClient( + credentials=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_security_settings), + '__call__') as call: + client.get_security_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.GetSecuritySettingsRequest() + + +@pytest.mark.asyncio +async def test_get_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.GetSecuritySettingsRequest): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + )) + response = await client.get_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.GetSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +@pytest.mark.asyncio +async def test_get_security_settings_async_from_dict(): + await test_get_security_settings_async(request_type=dict) + + +def test_get_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.GetSecuritySettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), + '__call__') as call: + call.return_value = security_settings.SecuritySettings() + client.get_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.GetSecuritySettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings()) + await client.get_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.SecuritySettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_security_settings( + name='name_value', + ) + + # Establish that the 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_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=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_security_settings( + security_settings.GetSecuritySettingsRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.SecuritySettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_security_settings( + 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_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_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_security_settings( + security_settings.GetSecuritySettingsRequest(), + name='name_value', + ) + + +def test_update_security_settings(transport: str = 'grpc', request_type=gcdc_security_settings.UpdateSecuritySettingsRequest): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + retention_window_days=2271, + ) + response = client.update_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +def test_update_security_settings_from_dict(): + test_update_security_settings(request_type=dict) + + +def test_update_security_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecuritySettingsServiceClient( + credentials=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_security_settings), + '__call__') as call: + client.update_security_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() + + +@pytest.mark.asyncio +async def test_update_security_settings_async(transport: str = 'grpc_asyncio', request_type=gcdc_security_settings.UpdateSecuritySettingsRequest): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + )) + response = await client.update_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +@pytest.mark.asyncio +async def test_update_security_settings_async_from_dict(): + await test_update_security_settings_async(request_type=dict) + + +def test_update_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_security_settings.UpdateSecuritySettingsRequest() + + request.security_settings.name = 'security_settings.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), + '__call__') as call: + call.return_value = gcdc_security_settings.SecuritySettings() + client.update_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_settings.name=security_settings.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_security_settings.UpdateSecuritySettingsRequest() + + request.security_settings.name = 'security_settings.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) + await client.update_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_settings.name=security_settings.name/value', + ) in kw['metadata'] + + +def test_update_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_settings( + security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=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_security_settings( + gcdc_security_settings.UpdateSecuritySettingsRequest(), + security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_settings( + security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_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_security_settings( + gcdc_security_settings.UpdateSecuritySettingsRequest(), + security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_security_settings(transport: str = 'grpc', request_type=security_settings.ListSecuritySettingsRequest): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.ListSecuritySettingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.ListSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecuritySettingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_security_settings_from_dict(): + test_list_security_settings(request_type=dict) + + +def test_list_security_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecuritySettingsServiceClient( + credentials=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_security_settings), + '__call__') as call: + client.list_security_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.ListSecuritySettingsRequest() + + +@pytest.mark.asyncio +async def test_list_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.ListSecuritySettingsRequest): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.ListSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecuritySettingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_security_settings_async_from_dict(): + await test_list_security_settings_async(request_type=dict) + + +def test_list_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.ListSecuritySettingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + call.return_value = security_settings.ListSecuritySettingsResponse() + client.list_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.ListSecuritySettingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse()) + await client.list_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.ListSecuritySettingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_security_settings( + parent='parent_value', + ) + + # Establish that the 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_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=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_security_settings( + security_settings.ListSecuritySettingsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.ListSecuritySettingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_security_settings( + 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_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_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_security_settings( + security_settings.ListSecuritySettingsRequest(), + parent='parent_value', + ) + + +def test_list_security_settings_pager(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token='abc', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], + next_page_token='def', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + ], + next_page_token='ghi', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_security_settings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, security_settings.SecuritySettings) + for i in results) + +def test_list_security_settings_pages(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token='abc', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], + next_page_token='def', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + ], + next_page_token='ghi', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + pages = list(client.list_security_settings(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_security_settings_async_pager(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token='abc', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], + next_page_token='def', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + ], + next_page_token='ghi', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_security_settings(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, security_settings.SecuritySettings) + for i in responses) + +@pytest.mark.asyncio +async def test_list_security_settings_async_pages(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token='abc', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], + next_page_token='def', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + ], + next_page_token='ghi', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_security_settings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_delete_security_settings(transport: str = 'grpc', request_type=security_settings.DeleteSecuritySettingsRequest): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.DeleteSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_security_settings_from_dict(): + test_delete_security_settings(request_type=dict) + + +def test_delete_security_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecuritySettingsServiceClient( + credentials=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_security_settings), + '__call__') as call: + client.delete_security_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.DeleteSecuritySettingsRequest() + + +@pytest.mark.asyncio +async def test_delete_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.DeleteSecuritySettingsRequest): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.DeleteSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_security_settings_async_from_dict(): + await test_delete_security_settings_async(request_type=dict) + + +def test_delete_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.DeleteSecuritySettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), + '__call__') as call: + call.return_value = None + client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.DeleteSecuritySettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), + '__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_security_settings( + 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_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=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_security_settings( + security_settings.DeleteSecuritySettingsRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), + '__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_security_settings( + 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_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_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_security_settings( + security_settings.DeleteSecuritySettingsRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecuritySettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecuritySettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecuritySettingsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecuritySettingsServiceGrpcTransport, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, +]) +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 = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecuritySettingsServiceGrpcTransport, + ) + +def test_security_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecuritySettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecuritySettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_security_settings', + 'get_security_settings', + 'update_security_settings', + 'list_security_settings', + 'delete_security_settings', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_security_settings_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecuritySettingsServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_security_settings_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecuritySettingsServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_security_settings_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecuritySettingsServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_security_settings_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SecuritySettingsServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_security_settings_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SecuritySettingsServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecuritySettingsServiceGrpcTransport, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_security_settings_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecuritySettingsServiceGrpcTransport, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_security_settings_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_security_settings_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_security_settings_service_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_security_settings_service_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) +def test_security_settings_service_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_security_settings_service_host_no_port(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_security_settings_service_host_with_port(): + client = SecuritySettingsServiceClient( + 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_security_settings_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecuritySettingsServiceGrpcTransport( + 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_security_settings_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( + 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.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) +def test_security_settings_service_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.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) +def test_security_settings_service_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_security_settings_path(): + project = "squid" + location = "clam" + security_settings = "whelk" + expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + actual = SecuritySettingsServiceClient.security_settings_path(project, location, security_settings) + assert expected == actual + + +def test_parse_security_settings_path(): + expected = { + "project": "octopus", + "location": "oyster", + "security_settings": "nudibranch", + } + path = SecuritySettingsServiceClient.security_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_security_settings_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecuritySettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SecuritySettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecuritySettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SecuritySettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecuritySettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SecuritySettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SecuritySettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SecuritySettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.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 = SecuritySettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SecuritySettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.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.SecuritySettingsServiceTransport, '_prep_wrapped_messages') as prep: + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecuritySettingsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SecuritySettingsServiceClient.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/v3/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py new file mode 100644 index 00000000..735e2642 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py @@ -0,0 +1,2373 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.session_entity_types import SessionEntityTypesAsyncClient +from google.cloud.dialogflowcx_v3.services.session_entity_types import SessionEntityTypesClient +from google.cloud.dialogflowcx_v3.services.session_entity_types import pagers +from google.cloud.dialogflowcx_v3.services.session_entity_types import transports +from google.cloud.dialogflowcx_v3.services.session_entity_types.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.session_entity_types.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type +from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3.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=gcdc_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 = gcdc_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + ) + response = client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +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] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_create_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + )) + response = await client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_session_entity_type.SessionEntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_session_entity_type( + parent='parent_value', + session_entity_type=gcdc_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 == gcdc_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( + gcdc_session_entity_type.CreateSessionEntityTypeRequest(), + parent='parent_value', + session_entity_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( + gcdc_session_entity_type.CreateSessionEntityTypeRequest(), + parent='parent_value', + session_entity_type=gcdc_session_entity_type.SessionEntityType(name='name_value'), + ) + + +def test_update_session_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + ) + response = client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +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] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_update_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + )) + response = await client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +@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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + + request.session_entity_type.name = 'session_entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + call.return_value = gcdc_session_entity_type.SessionEntityType() + client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + + request.session_entity_type.name = 'session_entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_session_entity_type.SessionEntityType()) + await client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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 = gcdc_session_entity_type.SessionEntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_session_entity_type( + session_entity_type=gcdc_session_entity_type.SessionEntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].session_entity_type == gcdc_session_entity_type.SessionEntityType(name='name_value') + assert args[0].update_mask == field_mask_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( + gcdc_session_entity_type.UpdateSessionEntityTypeRequest(), + session_entity_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( + gcdc_session_entity_type.UpdateSessionEntityTypeRequest(), + session_entity_type=gcdc_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.dialogflowcx_v3.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.dialogflowcx_v3.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + 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.dialogflowcx_v3.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" + location = "clam" + agent = "whelk" + session = "octopus" + entity_type = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, session=session, entity_type=entity_type, ) + actual = SessionEntityTypesClient.session_entity_type_path(project, location, agent, session, entity_type) + assert expected == actual + + +def test_parse_session_entity_type_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "session": "winkle", + "entity_type": "nautilus", + } + 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 = "scallop" + 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": "abalone", + } + 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 = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = SessionEntityTypesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + 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 = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SessionEntityTypesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + 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 = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = SessionEntityTypesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + 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": "winkle", + "location": "nautilus", + } + 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/v3/tests/unit/gapic/dialogflowcx_v3/test_sessions.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_sessions.py new file mode 100644 index 00000000..f365628e --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_sessions.py @@ -0,0 +1,1708 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.sessions import SessionsAsyncClient +from google.cloud.dialogflowcx_v3.services.sessions import SessionsClient +from google.cloud.dialogflowcx_v3.services.sessions import transports +from google.cloud.dialogflowcx_v3.services.sessions.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.sessions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import audio_config +from google.cloud.dialogflowcx_v3.types import entity_type +from google.cloud.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import session +from google.cloud.dialogflowcx_v3.types import session_entity_type +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # 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.dialogflowcx_v3.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=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 = session.DetectIntentResponse( + response_id='response_id_value', + output_audio=b'output_audio_blob', + ) + response = client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session.DetectIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.DetectIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +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] == session.DetectIntentRequest() + + +@pytest.mark.asyncio +async def test_detect_intent_async(transport: str = 'grpc_asyncio', request_type=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(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] == session.DetectIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.DetectIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +@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 = session.DetectIntentRequest() + + request.session = 'session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + call.return_value = session.DetectIntentResponse() + client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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 = 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(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_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_match_intent(transport: str = 'grpc', request_type=session.MatchIntentRequest): + 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.match_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session.MatchIntentResponse( + text='text_value', + ) + response = client.match_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session.MatchIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.MatchIntentResponse) + + +def test_match_intent_from_dict(): + test_match_intent(request_type=dict) + + +def test_match_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.match_intent), + '__call__') as call: + client.match_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session.MatchIntentRequest() + + +@pytest.mark.asyncio +async def test_match_intent_async(transport: str = 'grpc_asyncio', request_type=session.MatchIntentRequest): + 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.match_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session.MatchIntentResponse( + )) + response = await client.match_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == session.MatchIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.MatchIntentResponse) + + +@pytest.mark.asyncio +async def test_match_intent_async_from_dict(): + await test_match_intent_async(request_type=dict) + + +def test_match_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 = session.MatchIntentRequest() + + request.session = 'session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.match_intent), + '__call__') as call: + call.return_value = session.MatchIntentResponse() + client.match_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_match_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 = session.MatchIntentRequest() + + request.session = 'session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.match_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session.MatchIntentResponse()) + await client.match_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_fulfill_intent(transport: str = 'grpc', request_type=session.FulfillIntentRequest): + 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.fulfill_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session.FulfillIntentResponse( + response_id='response_id_value', + output_audio=b'output_audio_blob', + ) + response = client.fulfill_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session.FulfillIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.FulfillIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +def test_fulfill_intent_from_dict(): + test_fulfill_intent(request_type=dict) + + +def test_fulfill_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fulfill_intent), + '__call__') as call: + client.fulfill_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session.FulfillIntentRequest() + + +@pytest.mark.asyncio +async def test_fulfill_intent_async(transport: str = 'grpc_asyncio', request_type=session.FulfillIntentRequest): + 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.fulfill_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session.FulfillIntentResponse( + response_id='response_id_value', + output_audio=b'output_audio_blob', + )) + response = await client.fulfill_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == session.FulfillIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.FulfillIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +@pytest.mark.asyncio +async def test_fulfill_intent_async_from_dict(): + await test_fulfill_intent_async(request_type=dict) + + +def test_fulfill_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 = session.FulfillIntentRequest() + + request.match_intent_request.session = 'match_intent_request.session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fulfill_intent), + '__call__') as call: + call.return_value = session.FulfillIntentResponse() + client.fulfill_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'match_intent_request.session=match_intent_request.session/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_fulfill_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 = session.FulfillIntentRequest() + + request.match_intent_request.session = 'match_intent_request.session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fulfill_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session.FulfillIntentResponse()) + await client.fulfill_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'match_intent_request.session=match_intent_request.session/value', + ) in kw['metadata'] + + +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.dialogflowcx_v3.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', + 'match_intent', + 'fulfill_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.dialogflowcx_v3.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_sessions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (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.dialogflowcx_v3.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_entity_type_path(): + project = "squid" + location = "clam" + agent = "whelk" + entity_type = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + actual = SessionsClient.entity_type_path(project, location, agent, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "entity_type": "mussel", + } + path = SessionsClient.entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_entity_type_path(path) + assert expected == actual + +def test_flow_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + flow = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = SessionsClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "flow": "octopus", + } + path = SessionsClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_flow_path(path) + assert expected == actual + +def test_intent_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + intent = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = SessionsClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "intent": "abalone", + } + path = SessionsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_intent_path(path) + assert expected == actual + +def test_page_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + page = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + actual = SessionsClient.page_path(project, location, agent, flow, page) + assert expected == actual + + +def test_parse_page_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "flow": "winkle", + "page": "nautilus", + } + path = SessionsClient.page_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_page_path(path) + assert expected == actual + +def test_session_path(): + project = "scallop" + location = "abalone" + agent = "squid" + session = "clam" + expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format(project=project, location=location, agent=agent, session=session, ) + actual = SessionsClient.session_path(project, location, agent, session) + assert expected == actual + + +def test_parse_session_path(): + expected = { + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "session": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + agent = "winkle" + session = "nautilus" + entity_type = "scallop" + expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, session=session, entity_type=entity_type, ) + actual = SessionsClient.session_entity_type_path(project, location, agent, session, entity_type) + assert expected == actual + + +def test_parse_session_entity_type_path(): + expected = { + "project": "abalone", + "location": "squid", + "agent": "clam", + "session": "whelk", + "entity_type": "octopus", + } + 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_transition_route_group_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + flow = "mussel" + transition_route_group = "winkle" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + actual = SessionsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) + assert expected == actual + + +def test_parse_transition_route_group_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "agent": "abalone", + "flow": "squid", + "transition_route_group": "clam", + } + path = SessionsClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_transition_route_group_path(path) + assert expected == actual + +def test_webhook_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + webhook = "nudibranch" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = SessionsClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "webhook": "nautilus", + } + path = SessionsClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + 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": "abalone", + } + 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 = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = SessionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + 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 = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SessionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + 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 = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = SessionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + 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": "winkle", + "location": "nautilus", + } + 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/v3/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py new file mode 100644 index 00000000..423c4fa3 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py @@ -0,0 +1,4061 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.test_cases import TestCasesAsyncClient +from google.cloud.dialogflowcx_v3.services.test_cases import TestCasesClient +from google.cloud.dialogflowcx_v3.services.test_cases import pagers +from google.cloud.dialogflowcx_v3.services.test_cases import transports +from google.cloud.dialogflowcx_v3.services.test_cases.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.test_cases.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import audio_config +from google.cloud.dialogflowcx_v3.types import fulfillment +from google.cloud.dialogflowcx_v3.types import intent +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import response_message +from google.cloud.dialogflowcx_v3.types import session +from google.cloud.dialogflowcx_v3.types import test_case +from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 +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 struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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 TestCasesClient._get_default_mtls_endpoint(None) is None + assert TestCasesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TestCasesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TestCasesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TestCasesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TestCasesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + TestCasesClient, + TestCasesAsyncClient, +]) +def test_test_cases_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", [ + TestCasesClient, + TestCasesAsyncClient, +]) +def test_test_cases_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_test_cases_client_get_transport_class(): + transport = TestCasesClient.get_transport_class() + available_transports = [ + transports.TestCasesGrpcTransport, + ] + assert transport in available_transports + + transport = TestCasesClient.get_transport_class("grpc") + assert transport == transports.TestCasesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), + (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(TestCasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesClient)) +@mock.patch.object(TestCasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesAsyncClient)) +def test_test_cases_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(TestCasesClient, '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(TestCasesClient, '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", [ + (TestCasesClient, transports.TestCasesGrpcTransport, "grpc", "true"), + (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TestCasesClient, transports.TestCasesGrpcTransport, "grpc", "false"), + (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(TestCasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesClient)) +@mock.patch.object(TestCasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_test_cases_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", [ + (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), + (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_test_cases_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", [ + (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), + (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_test_cases_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_test_cases_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TestCasesClient( + 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_test_cases(transport: str = 'grpc', request_type=test_case.ListTestCasesRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCasesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTestCasesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_test_cases_from_dict(): + test_list_test_cases(request_type=dict) + + +def test_list_test_cases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_cases), + '__call__') as call: + client.list_test_cases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCasesRequest() + + +@pytest.mark.asyncio +async def test_list_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ListTestCasesRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTestCasesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_test_cases_async_from_dict(): + await test_list_test_cases_async(request_type=dict) + + +def test_list_test_cases_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ListTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + call.return_value = test_case.ListTestCasesResponse() + client.list_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_cases_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ListTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse()) + await client.list_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_cases_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCasesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_test_cases( + parent='parent_value', + ) + + # Establish that the 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_test_cases_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_test_cases( + test_case.ListTestCasesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_test_cases_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCasesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_test_cases( + 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_test_cases_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_test_cases( + test_case.ListTestCasesRequest(), + parent='parent_value', + ) + + +def test_list_test_cases_pager(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + test_case.TestCase(), + ], + next_page_token='abc', + ), + test_case.ListTestCasesResponse( + test_cases=[], + next_page_token='def', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + ], + next_page_token='ghi', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_test_cases(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, test_case.TestCase) + for i in results) + +def test_list_test_cases_pages(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + test_case.TestCase(), + ], + next_page_token='abc', + ), + test_case.ListTestCasesResponse( + test_cases=[], + next_page_token='def', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + ], + next_page_token='ghi', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + ], + ), + RuntimeError, + ) + pages = list(client.list_test_cases(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_test_cases_async_pager(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + test_case.TestCase(), + ], + next_page_token='abc', + ), + test_case.ListTestCasesResponse( + test_cases=[], + next_page_token='def', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + ], + next_page_token='ghi', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_test_cases(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, test_case.TestCase) + for i in responses) + +@pytest.mark.asyncio +async def test_list_test_cases_async_pages(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + test_case.TestCase(), + ], + next_page_token='abc', + ), + test_case.ListTestCasesResponse( + test_cases=[], + next_page_token='def', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + ], + next_page_token='ghi', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_test_cases(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_batch_delete_test_cases(transport: str = 'grpc', request_type=test_case.BatchDeleteTestCasesRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.batch_delete_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchDeleteTestCasesRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_batch_delete_test_cases_from_dict(): + test_batch_delete_test_cases(request_type=dict) + + +def test_batch_delete_test_cases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_cases), + '__call__') as call: + client.batch_delete_test_cases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchDeleteTestCasesRequest() + + +@pytest.mark.asyncio +async def test_batch_delete_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.BatchDeleteTestCasesRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.batch_delete_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchDeleteTestCasesRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_batch_delete_test_cases_async_from_dict(): + await test_batch_delete_test_cases_async(request_type=dict) + + +def test_batch_delete_test_cases_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.BatchDeleteTestCasesRequest() + + 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_test_cases), + '__call__') as call: + call.return_value = None + client.batch_delete_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_cases_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.BatchDeleteTestCasesRequest() + + 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_test_cases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.batch_delete_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_cases_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_test_cases), + '__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.batch_delete_test_cases( + 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_delete_test_cases_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_test_cases( + test_case.BatchDeleteTestCasesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_batch_delete_test_cases_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_test_cases), + '__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.batch_delete_test_cases( + 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_delete_test_cases_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_delete_test_cases( + test_case.BatchDeleteTestCasesRequest(), + parent='parent_value', + ) + + +def test_get_test_case(transport: str = 'grpc', request_type=test_case.GetTestCaseRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + ) + response = client.get_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +def test_get_test_case_from_dict(): + test_get_test_case(request_type=dict) + + +def test_get_test_case_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + client.get_test_case() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseRequest() + + +@pytest.mark.asyncio +async def test_get_test_case_async(transport: str = 'grpc_asyncio', request_type=test_case.GetTestCaseRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + )) + response = await client.get_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +@pytest.mark.asyncio +async def test_get_test_case_async_from_dict(): + await test_get_test_case_async(request_type=dict) + + +def test_get_test_case_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.GetTestCaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + call.return_value = test_case.TestCase() + client.get_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_test_case_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.GetTestCaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase()) + await client.get_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_test_case_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_test_case( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_test_case_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_test_case( + test_case.GetTestCaseRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_test_case_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_test_case( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_test_case_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_test_case( + test_case.GetTestCaseRequest(), + name='name_value', + ) + + +def test_create_test_case(transport: str = 'grpc', request_type=gcdc_test_case.CreateTestCaseRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + ) + response = client.create_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.CreateTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +def test_create_test_case_from_dict(): + test_create_test_case(request_type=dict) + + +def test_create_test_case_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_case), + '__call__') as call: + client.create_test_case() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.CreateTestCaseRequest() + + +@pytest.mark.asyncio +async def test_create_test_case_async(transport: str = 'grpc_asyncio', request_type=gcdc_test_case.CreateTestCaseRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + )) + response = await client.create_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.CreateTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +@pytest.mark.asyncio +async def test_create_test_case_async_from_dict(): + await test_create_test_case_async(request_type=dict) + + +def test_create_test_case_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_test_case.CreateTestCaseRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + call.return_value = gcdc_test_case.TestCase() + client.create_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_case_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_test_case.CreateTestCaseRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) + await client.create_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_case_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_test_case( + parent='parent_value', + test_case=gcdc_test_case.TestCase(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].test_case == gcdc_test_case.TestCase(name='name_value') + + +def test_create_test_case_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_test_case( + gcdc_test_case.CreateTestCaseRequest(), + parent='parent_value', + test_case=gcdc_test_case.TestCase(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_test_case_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_test_case( + parent='parent_value', + test_case=gcdc_test_case.TestCase(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].test_case == gcdc_test_case.TestCase(name='name_value') + + +@pytest.mark.asyncio +async def test_create_test_case_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_test_case( + gcdc_test_case.CreateTestCaseRequest(), + parent='parent_value', + test_case=gcdc_test_case.TestCase(name='name_value'), + ) + + +def test_update_test_case(transport: str = 'grpc', request_type=gcdc_test_case.UpdateTestCaseRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + ) + response = client.update_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.UpdateTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +def test_update_test_case_from_dict(): + test_update_test_case(request_type=dict) + + +def test_update_test_case_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_case), + '__call__') as call: + client.update_test_case() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.UpdateTestCaseRequest() + + +@pytest.mark.asyncio +async def test_update_test_case_async(transport: str = 'grpc_asyncio', request_type=gcdc_test_case.UpdateTestCaseRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + )) + response = await client.update_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.UpdateTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +@pytest.mark.asyncio +async def test_update_test_case_async_from_dict(): + await test_update_test_case_async(request_type=dict) + + +def test_update_test_case_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_test_case.UpdateTestCaseRequest() + + request.test_case.name = 'test_case.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + call.return_value = gcdc_test_case.TestCase() + client.update_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'test_case.name=test_case.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_test_case_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_test_case.UpdateTestCaseRequest() + + request.test_case.name = 'test_case.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) + await client.update_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'test_case.name=test_case.name/value', + ) in kw['metadata'] + + +def test_update_test_case_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_test_case( + test_case=gcdc_test_case.TestCase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].test_case == gcdc_test_case.TestCase(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_test_case_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_test_case( + gcdc_test_case.UpdateTestCaseRequest(), + test_case=gcdc_test_case.TestCase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_test_case_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_test_case( + test_case=gcdc_test_case.TestCase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].test_case == gcdc_test_case.TestCase(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_test_case_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_test_case( + gcdc_test_case.UpdateTestCaseRequest(), + test_case=gcdc_test_case.TestCase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_run_test_case(transport: str = 'grpc', request_type=test_case.RunTestCaseRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.RunTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_test_case_from_dict(): + test_run_test_case(request_type=dict) + + +def test_run_test_case_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_test_case), + '__call__') as call: + client.run_test_case() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.RunTestCaseRequest() + + +@pytest.mark.asyncio +async def test_run_test_case_async(transport: str = 'grpc_asyncio', request_type=test_case.RunTestCaseRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_test_case), + '__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.run_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.RunTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_test_case_async_from_dict(): + await test_run_test_case_async(request_type=dict) + + +def test_run_test_case_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.RunTestCaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_test_case), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_run_test_case_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.RunTestCaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_test_case), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_batch_run_test_cases(transport: str = 'grpc', request_type=test_case.BatchRunTestCasesRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_run_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchRunTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_run_test_cases_from_dict(): + test_batch_run_test_cases(request_type=dict) + + +def test_batch_run_test_cases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_run_test_cases), + '__call__') as call: + client.batch_run_test_cases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchRunTestCasesRequest() + + +@pytest.mark.asyncio +async def test_batch_run_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.BatchRunTestCasesRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_test_cases), + '__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_run_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchRunTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_run_test_cases_async_from_dict(): + await test_batch_run_test_cases_async(request_type=dict) + + +def test_batch_run_test_cases_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.BatchRunTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_test_cases), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_run_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_run_test_cases_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.BatchRunTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_test_cases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_run_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_calculate_coverage(transport: str = 'grpc', request_type=test_case.CalculateCoverageRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.calculate_coverage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.CalculateCoverageResponse( + agent='agent_value', + intent_coverage=test_case.IntentCoverage(intents=[test_case.IntentCoverage.Intent(intent='intent_value')]), + ) + response = client.calculate_coverage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.CalculateCoverageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.CalculateCoverageResponse) + assert response.agent == 'agent_value' + + +def test_calculate_coverage_from_dict(): + test_calculate_coverage(request_type=dict) + + +def test_calculate_coverage_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.calculate_coverage), + '__call__') as call: + client.calculate_coverage() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.CalculateCoverageRequest() + + +@pytest.mark.asyncio +async def test_calculate_coverage_async(transport: str = 'grpc_asyncio', request_type=test_case.CalculateCoverageRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.calculate_coverage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.CalculateCoverageResponse( + agent='agent_value', + )) + response = await client.calculate_coverage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.CalculateCoverageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.CalculateCoverageResponse) + assert response.agent == 'agent_value' + + +@pytest.mark.asyncio +async def test_calculate_coverage_async_from_dict(): + await test_calculate_coverage_async(request_type=dict) + + +def test_calculate_coverage_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.CalculateCoverageRequest() + + request.agent = 'agent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.calculate_coverage), + '__call__') as call: + call.return_value = test_case.CalculateCoverageResponse() + client.calculate_coverage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=agent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_calculate_coverage_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.CalculateCoverageRequest() + + request.agent = 'agent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.calculate_coverage), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.CalculateCoverageResponse()) + await client.calculate_coverage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'agent=agent/value', + ) in kw['metadata'] + + +def test_import_test_cases(transport: str = 'grpc', request_type=test_case.ImportTestCasesRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ImportTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_test_cases_from_dict(): + test_import_test_cases(request_type=dict) + + +def test_import_test_cases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_cases), + '__call__') as call: + client.import_test_cases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ImportTestCasesRequest() + + +@pytest.mark.asyncio +async def test_import_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ImportTestCasesRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_test_cases), + '__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_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ImportTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_test_cases_async_from_dict(): + await test_import_test_cases_async(request_type=dict) + + +def test_import_test_cases_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ImportTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_test_cases), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_cases_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ImportTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_test_cases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_cases(transport: str = 'grpc', request_type=test_case.ExportTestCasesRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ExportTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_test_cases_from_dict(): + test_export_test_cases(request_type=dict) + + +def test_export_test_cases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_cases), + '__call__') as call: + client.export_test_cases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ExportTestCasesRequest() + + +@pytest.mark.asyncio +async def test_export_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ExportTestCasesRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_test_cases), + '__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_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ExportTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_test_cases_async_from_dict(): + await test_export_test_cases_async(request_type=dict) + + +def test_export_test_cases_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ExportTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_test_cases), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_cases_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ExportTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_test_cases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_case_results(transport: str = 'grpc', request_type=test_case.ListTestCaseResultsRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCaseResultsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_test_case_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCaseResultsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTestCaseResultsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_test_case_results_from_dict(): + test_list_test_case_results(request_type=dict) + + +def test_list_test_case_results_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_case_results), + '__call__') as call: + client.list_test_case_results() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCaseResultsRequest() + + +@pytest.mark.asyncio +async def test_list_test_case_results_async(transport: str = 'grpc_asyncio', request_type=test_case.ListTestCaseResultsRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_test_case_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCaseResultsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTestCaseResultsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_test_case_results_async_from_dict(): + await test_list_test_case_results_async(request_type=dict) + + +def test_list_test_case_results_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ListTestCaseResultsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + call.return_value = test_case.ListTestCaseResultsResponse() + client.list_test_case_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_case_results_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ListTestCaseResultsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse()) + await client.list_test_case_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_case_results_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCaseResultsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_test_case_results( + parent='parent_value', + ) + + # Establish that the 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_test_case_results_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_test_case_results( + test_case.ListTestCaseResultsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_test_case_results_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCaseResultsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_test_case_results( + 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_test_case_results_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_test_case_results( + test_case.ListTestCaseResultsRequest(), + parent='parent_value', + ) + + +def test_list_test_case_results_pager(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + next_page_token='abc', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[], + next_page_token='def', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + ], + next_page_token='ghi', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_test_case_results(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, test_case.TestCaseResult) + for i in results) + +def test_list_test_case_results_pages(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + next_page_token='abc', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[], + next_page_token='def', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + ], + next_page_token='ghi', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_test_case_results(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_test_case_results_async_pager(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + next_page_token='abc', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[], + next_page_token='def', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + ], + next_page_token='ghi', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_test_case_results(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, test_case.TestCaseResult) + for i in responses) + +@pytest.mark.asyncio +async def test_list_test_case_results_async_pages(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + next_page_token='abc', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[], + next_page_token='def', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + ], + next_page_token='ghi', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_test_case_results(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_test_case_result(transport: str = 'grpc', request_type=test_case.GetTestCaseResultRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult( + name='name_value', + environment='environment_value', + test_result=test_case.TestResult.PASSED, + ) + response = client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCaseResult) + assert response.name == 'name_value' + assert response.environment == 'environment_value' + assert response.test_result == test_case.TestResult.PASSED + + +def test_get_test_case_result_from_dict(): + test_get_test_case_result(request_type=dict) + + +def test_get_test_case_result_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + client.get_test_case_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + +@pytest.mark.asyncio +async def test_get_test_case_result_async(transport: str = 'grpc_asyncio', request_type=test_case.GetTestCaseResultRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult( + name='name_value', + environment='environment_value', + test_result=test_case.TestResult.PASSED, + )) + response = await client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCaseResult) + assert response.name == 'name_value' + assert response.environment == 'environment_value' + assert response.test_result == test_case.TestResult.PASSED + + +@pytest.mark.asyncio +async def test_get_test_case_result_async_from_dict(): + await test_get_test_case_result_async(request_type=dict) + + +def test_get_test_case_result_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.GetTestCaseResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + call.return_value = test_case.TestCaseResult() + client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_test_case_result_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.GetTestCaseResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult()) + await client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_test_case_result_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_test_case_result( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_test_case_result_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_test_case_result( + test_case.GetTestCaseResultRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_test_case_result_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_test_case_result( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_test_case_result_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_test_case_result( + test_case.GetTestCaseResultRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TestCasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TestCasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TestCasesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TestCasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TestCasesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TestCasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TestCasesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TestCasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TestCasesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TestCasesGrpcTransport, + transports.TestCasesGrpcAsyncIOTransport, +]) +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 = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TestCasesGrpcTransport, + ) + +def test_test_cases_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TestCasesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_test_cases_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TestCasesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_test_cases', + 'batch_delete_test_cases', + 'get_test_case', + 'create_test_case', + 'update_test_case', + 'run_test_case', + 'batch_run_test_cases', + 'calculate_coverage', + 'import_test_cases', + 'export_test_cases', + 'list_test_case_results', + 'get_test_case_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_test_cases_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TestCasesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_test_cases_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TestCasesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_test_cases_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TestCasesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_test_cases_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TestCasesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_test_cases_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TestCasesClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TestCasesGrpcTransport, + transports.TestCasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_test_cases_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TestCasesGrpcTransport, + transports.TestCasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_test_cases_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_test_cases_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_test_cases_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_test_cases_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) +def test_test_cases_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = 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_test_cases_host_no_port(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_test_cases_host_with_port(): + client = TestCasesClient( + 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_test_cases_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TestCasesGrpcTransport( + 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_test_cases_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TestCasesGrpcAsyncIOTransport( + 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.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) +def test_test_cases_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.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) +def test_test_cases_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_test_cases_grpc_lro_client(): + client = TestCasesClient( + 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_test_cases_grpc_lro_async_client(): + client = TestCasesAsyncClient( + 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" + location = "clam" + agent = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) + actual = TestCasesClient.agent_path(project, location, agent) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + } + path = TestCasesClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_agent_path(path) + assert expected == actual + +def test_entity_type_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + entity_type = "nautilus" + expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + actual = TestCasesClient.entity_type_path(project, location, agent, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "scallop", + "location": "abalone", + "agent": "squid", + "entity_type": "clam", + } + path = TestCasesClient.entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_entity_type_path(path) + assert expected == actual + +def test_environment_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + environment = "nudibranch" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + actual = TestCasesClient.environment_path(project, location, agent, environment) + assert expected == actual + + +def test_parse_environment_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "environment": "nautilus", + } + path = TestCasesClient.environment_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_environment_path(path) + assert expected == actual + +def test_flow_path(): + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = TestCasesClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "flow": "nudibranch", + } + path = TestCasesClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_flow_path(path) + assert expected == actual + +def test_intent_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + intent = "nautilus" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = TestCasesClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "scallop", + "location": "abalone", + "agent": "squid", + "intent": "clam", + } + path = TestCasesClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_intent_path(path) + assert expected == actual + +def test_page_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + flow = "nudibranch" + page = "cuttlefish" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + actual = TestCasesClient.page_path(project, location, agent, flow, page) + assert expected == actual + + +def test_parse_page_path(): + expected = { + "project": "mussel", + "location": "winkle", + "agent": "nautilus", + "flow": "scallop", + "page": "abalone", + } + path = TestCasesClient.page_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_page_path(path) + assert expected == actual + +def test_test_case_path(): + project = "squid" + location = "clam" + agent = "whelk" + test_case = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(project=project, location=location, agent=agent, test_case=test_case, ) + actual = TestCasesClient.test_case_path(project, location, agent, test_case) + assert expected == actual + + +def test_parse_test_case_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "test_case": "mussel", + } + path = TestCasesClient.test_case_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_test_case_path(path) + assert expected == actual + +def test_test_case_result_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + test_case = "abalone" + result = "squid" + expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) + actual = TestCasesClient.test_case_result_path(project, location, agent, test_case, result) + assert expected == actual + + +def test_parse_test_case_result_path(): + expected = { + "project": "clam", + "location": "whelk", + "agent": "octopus", + "test_case": "oyster", + "result": "nudibranch", + } + path = TestCasesClient.test_case_result_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_test_case_result_path(path) + assert expected == actual + +def test_transition_route_group_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + flow = "nautilus" + transition_route_group = "scallop" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + actual = TestCasesClient.transition_route_group_path(project, location, agent, flow, transition_route_group) + assert expected == actual + + +def test_parse_transition_route_group_path(): + expected = { + "project": "abalone", + "location": "squid", + "agent": "clam", + "flow": "whelk", + "transition_route_group": "octopus", + } + path = TestCasesClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_transition_route_group_path(path) + assert expected == actual + +def test_webhook_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + webhook = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = TestCasesClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "webhook": "abalone", + } + path = TestCasesClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TestCasesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = TestCasesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = TestCasesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = TestCasesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TestCasesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = TestCasesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = TestCasesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = TestCasesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = TestCasesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = TestCasesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.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.TestCasesTransport, '_prep_wrapped_messages') as prep: + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TestCasesTransport, '_prep_wrapped_messages') as prep: + transport_class = TestCasesClient.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/v3/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py new file mode 100644 index 00000000..3f30ccc2 --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py @@ -0,0 +1,2470 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.transition_route_groups import TransitionRouteGroupsAsyncClient +from google.cloud.dialogflowcx_v3.services.transition_route_groups import TransitionRouteGroupsClient +from google.cloud.dialogflowcx_v3.services.transition_route_groups import pagers +from google.cloud.dialogflowcx_v3.services.transition_route_groups import transports +from google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import fulfillment +from google.cloud.dialogflowcx_v3.types import page +from google.cloud.dialogflowcx_v3.types import response_message +from google.cloud.dialogflowcx_v3.types import transition_route_group +from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group +from google.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 TransitionRouteGroupsClient._get_default_mtls_endpoint(None) is None + assert TransitionRouteGroupsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TransitionRouteGroupsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TransitionRouteGroupsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TransitionRouteGroupsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TransitionRouteGroupsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + TransitionRouteGroupsClient, + TransitionRouteGroupsAsyncClient, +]) +def test_transition_route_groups_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", [ + TransitionRouteGroupsClient, + TransitionRouteGroupsAsyncClient, +]) +def test_transition_route_groups_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_transition_route_groups_client_get_transport_class(): + transport = TransitionRouteGroupsClient.get_transport_class() + available_transports = [ + transports.TransitionRouteGroupsGrpcTransport, + ] + assert transport in available_transports + + transport = TransitionRouteGroupsClient.get_transport_class("grpc") + assert transport == transports.TransitionRouteGroupsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), + (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(TransitionRouteGroupsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsClient)) +@mock.patch.object(TransitionRouteGroupsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsAsyncClient)) +def test_transition_route_groups_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(TransitionRouteGroupsClient, '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(TransitionRouteGroupsClient, '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", [ + (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc", "true"), + (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc", "false"), + (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(TransitionRouteGroupsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsClient)) +@mock.patch.object(TransitionRouteGroupsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_transition_route_groups_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", [ + (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), + (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_transition_route_groups_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", [ + (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), + (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_transition_route_groups_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_transition_route_groups_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TransitionRouteGroupsClient( + 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_transition_route_groups(transport: str = 'grpc', request_type=transition_route_group.ListTransitionRouteGroupsRequest): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.ListTransitionRouteGroupsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_transition_route_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransitionRouteGroupsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_transition_route_groups_from_dict(): + test_list_transition_route_groups(request_type=dict) + + +def test_list_transition_route_groups_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TransitionRouteGroupsClient( + credentials=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_transition_route_groups), + '__call__') as call: + client.list_transition_route_groups() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() + + +@pytest.mark.asyncio +async def test_list_transition_route_groups_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.ListTransitionRouteGroupsRequest): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_transition_route_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransitionRouteGroupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_transition_route_groups_async_from_dict(): + await test_list_transition_route_groups_async(request_type=dict) + + +def test_list_transition_route_groups_field_headers(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.ListTransitionRouteGroupsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() + client.list_transition_route_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_transition_route_groups_field_headers_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.ListTransitionRouteGroupsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse()) + await client.list_transition_route_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_transition_route_groups_flattened(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_transition_route_groups( + parent='parent_value', + ) + + # Establish that the 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_transition_route_groups_flattened_error(): + client = TransitionRouteGroupsClient( + credentials=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_transition_route_groups( + transition_route_group.ListTransitionRouteGroupsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_transition_route_groups_flattened_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_transition_route_groups( + 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_transition_route_groups_flattened_error_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_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_transition_route_groups( + transition_route_group.ListTransitionRouteGroupsRequest(), + parent='parent_value', + ) + + +def test_list_transition_route_groups_pager(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='abc', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[], + next_page_token='def', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='ghi', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_transition_route_groups(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, transition_route_group.TransitionRouteGroup) + for i in results) + +def test_list_transition_route_groups_pages(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='abc', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[], + next_page_token='def', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='ghi', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_transition_route_groups(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_transition_route_groups_async_pager(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='abc', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[], + next_page_token='def', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='ghi', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_transition_route_groups(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, transition_route_group.TransitionRouteGroup) + for i in responses) + +@pytest.mark.asyncio +async def test_list_transition_route_groups_async_pages(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='abc', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[], + next_page_token='def', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='ghi', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_transition_route_groups(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_transition_route_group(transport: str = 'grpc', request_type=transition_route_group.GetTransitionRouteGroupRequest): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + ) + response = client.get_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_get_transition_route_group_from_dict(): + test_get_transition_route_group(request_type=dict) + + +def test_get_transition_route_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group), + '__call__') as call: + client.get_transition_route_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() + + +@pytest.mark.asyncio +async def test_get_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.GetTransitionRouteGroupRequest): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + )) + response = await client.get_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_transition_route_group_async_from_dict(): + await test_get_transition_route_group_async(request_type=dict) + + +def test_get_transition_route_group_field_headers(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.GetTransitionRouteGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transition_route_group), + '__call__') as call: + call.return_value = transition_route_group.TransitionRouteGroup() + client.get_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_transition_route_group_field_headers_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.GetTransitionRouteGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transition_route_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup()) + await client.get_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_transition_route_group_flattened(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.TransitionRouteGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_transition_route_group( + name='name_value', + ) + + # Establish that the 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_transition_route_group_flattened_error(): + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group( + transition_route_group.GetTransitionRouteGroupRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_transition_route_group_flattened_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.TransitionRouteGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_transition_route_group( + 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_transition_route_group_flattened_error_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_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_transition_route_group( + transition_route_group.GetTransitionRouteGroupRequest(), + name='name_value', + ) + + +def test_create_transition_route_group(transport: str = 'grpc', request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + ) + response = client.create_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_create_transition_route_group_from_dict(): + test_create_transition_route_group(request_type=dict) + + +def test_create_transition_route_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group), + '__call__') as call: + client.create_transition_route_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + + +@pytest.mark.asyncio +async def test_create_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + )) + response = await client.create_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_create_transition_route_group_async_from_dict(): + await test_create_transition_route_group_async(request_type=dict) + + +def test_create_transition_route_group_field_headers(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transition_route_group), + '__call__') as call: + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + client.create_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_transition_route_group_field_headers_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transition_route_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) + await client.create_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_transition_route_group_flattened(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_transition_route_group( + parent='parent_value', + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') + + +def test_create_transition_route_group_flattened_error(): + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group( + gcdc_transition_route_group.CreateTransitionRouteGroupRequest(), + parent='parent_value', + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_transition_route_group_flattened_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_transition_route_group( + parent='parent_value', + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') + + +@pytest.mark.asyncio +async def test_create_transition_route_group_flattened_error_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_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_transition_route_group( + gcdc_transition_route_group.CreateTransitionRouteGroupRequest(), + parent='parent_value', + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), + ) + + +def test_update_transition_route_group(transport: str = 'grpc', request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + ) + response = client.update_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_transition_route_group_from_dict(): + test_update_transition_route_group(request_type=dict) + + +def test_update_transition_route_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group), + '__call__') as call: + client.update_transition_route_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + + +@pytest.mark.asyncio +async def test_update_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_transition_route_group_async_from_dict(): + await test_update_transition_route_group_async(request_type=dict) + + +def test_update_transition_route_group_field_headers(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + + request.transition_route_group.name = 'transition_route_group.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transition_route_group), + '__call__') as call: + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + client.update_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'transition_route_group.name=transition_route_group.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_transition_route_group_field_headers_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + + request.transition_route_group.name = 'transition_route_group.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transition_route_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) + await client.update_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'transition_route_group.name=transition_route_group.name/value', + ) in kw['metadata'] + + +def test_update_transition_route_group_flattened(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_transition_route_group( + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_transition_route_group_flattened_error(): + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group( + gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(), + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_transition_route_group_flattened_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_transition_route_group( + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_transition_route_group_flattened_error_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_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_transition_route_group( + gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(), + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_transition_route_group(transport: str = 'grpc', request_type=transition_route_group.DeleteTransitionRouteGroupRequest): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_transition_route_group_from_dict(): + test_delete_transition_route_group(request_type=dict) + + +def test_delete_transition_route_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group), + '__call__') as call: + client.delete_transition_route_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() + + +@pytest.mark.asyncio +async def test_delete_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.DeleteTransitionRouteGroupRequest): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_transition_route_group_async_from_dict(): + await test_delete_transition_route_group_async(request_type=dict) + + +def test_delete_transition_route_group_field_headers(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.DeleteTransitionRouteGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transition_route_group), + '__call__') as call: + call.return_value = None + client.delete_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_transition_route_group_field_headers_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.DeleteTransitionRouteGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transition_route_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_transition_route_group_flattened(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transition_route_group), + '__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_transition_route_group( + 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_transition_route_group_flattened_error(): + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group( + transition_route_group.DeleteTransitionRouteGroupRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_transition_route_group_flattened_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transition_route_group), + '__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_transition_route_group( + 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_transition_route_group_flattened_error_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_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_transition_route_group( + transition_route_group.DeleteTransitionRouteGroupRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TransitionRouteGroupsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TransitionRouteGroupsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TransitionRouteGroupsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TransitionRouteGroupsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TransitionRouteGroupsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TransitionRouteGroupsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TransitionRouteGroupsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TransitionRouteGroupsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TransitionRouteGroupsGrpcTransport, + transports.TransitionRouteGroupsGrpcAsyncIOTransport, +]) +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 = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TransitionRouteGroupsGrpcTransport, + ) + +def test_transition_route_groups_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TransitionRouteGroupsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_transition_route_groups_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TransitionRouteGroupsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_transition_route_groups', + 'get_transition_route_group', + 'create_transition_route_group', + 'update_transition_route_group', + 'delete_transition_route_group', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_transition_route_groups_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TransitionRouteGroupsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_transition_route_groups_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TransitionRouteGroupsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_transition_route_groups_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TransitionRouteGroupsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_transition_route_groups_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TransitionRouteGroupsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_transition_route_groups_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TransitionRouteGroupsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TransitionRouteGroupsGrpcTransport, + transports.TransitionRouteGroupsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_transition_route_groups_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TransitionRouteGroupsGrpcTransport, + transports.TransitionRouteGroupsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_transition_route_groups_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_transition_route_groups_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_transition_route_groups_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_transition_route_groups_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) +def test_transition_route_groups_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_transition_route_groups_host_no_port(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_transition_route_groups_host_with_port(): + client = TransitionRouteGroupsClient( + 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_transition_route_groups_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TransitionRouteGroupsGrpcTransport( + 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_transition_route_groups_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport( + 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.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) +def test_transition_route_groups_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.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) +def test_transition_route_groups_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_flow_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = TransitionRouteGroupsClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "flow": "mussel", + } + path = TransitionRouteGroupsClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_flow_path(path) + assert expected == actual + +def test_intent_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + intent = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = TransitionRouteGroupsClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "intent": "octopus", + } + path = TransitionRouteGroupsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_intent_path(path) + assert expected == actual + +def test_page_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + flow = "mussel" + page = "winkle" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + actual = TransitionRouteGroupsClient.page_path(project, location, agent, flow, page) + assert expected == actual + + +def test_parse_page_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "agent": "abalone", + "flow": "squid", + "page": "clam", + } + path = TransitionRouteGroupsClient.page_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_page_path(path) + assert expected == actual + +def test_transition_route_group_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + flow = "nudibranch" + transition_route_group = "cuttlefish" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + actual = TransitionRouteGroupsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) + assert expected == actual + + +def test_parse_transition_route_group_path(): + expected = { + "project": "mussel", + "location": "winkle", + "agent": "nautilus", + "flow": "scallop", + "transition_route_group": "abalone", + } + path = TransitionRouteGroupsClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_transition_route_group_path(path) + assert expected == actual + +def test_webhook_path(): + project = "squid" + location = "clam" + agent = "whelk" + webhook = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = TransitionRouteGroupsClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "webhook": "mussel", + } + path = TransitionRouteGroupsClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TransitionRouteGroupsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = TransitionRouteGroupsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = TransitionRouteGroupsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = TransitionRouteGroupsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TransitionRouteGroupsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = TransitionRouteGroupsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = TransitionRouteGroupsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = TransitionRouteGroupsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.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 = TransitionRouteGroupsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = TransitionRouteGroupsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.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.TransitionRouteGroupsTransport, '_prep_wrapped_messages') as prep: + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TransitionRouteGroupsTransport, '_prep_wrapped_messages') as prep: + transport_class = TransitionRouteGroupsClient.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/v3/tests/unit/gapic/dialogflowcx_v3/test_versions.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_versions.py new file mode 100644 index 00000000..c523b41d --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_versions.py @@ -0,0 +1,2658 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.versions import VersionsAsyncClient +from google.cloud.dialogflowcx_v3.services.versions import VersionsClient +from google.cloud.dialogflowcx_v3.services.versions import pagers +from google.cloud.dialogflowcx_v3.services.versions import transports +from google.cloud.dialogflowcx_v3.services.versions.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.versions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import flow +from google.cloud.dialogflowcx_v3.types import version +from google.cloud.dialogflowcx_v3.types import version as gcdc_version +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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(): + 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.dialogflowcx_v3.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', + display_name='display_name_value', + description='description_value', + state=version.Version.State.RUNNING, + ) + response = client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == version.Version.State.RUNNING + + +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', + display_name='display_name_value', + description='description_value', + state=version.Version.State.RUNNING, + )) + response = await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == version.Version.State.RUNNING + + +@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=gcdc_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 = operations_pb2.Operation(name='operations/spam') + response = client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +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] == gcdc_version.CreateVersionRequest() + + +@pytest.mark.asyncio +async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@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 = gcdc_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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 = gcdc_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + 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 = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_version( + parent='parent_value', + version=gcdc_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 == gcdc_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( + gcdc_version.CreateVersionRequest(), + parent='parent_value', + version=gcdc_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 = 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_version( + parent='parent_value', + version=gcdc_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 == gcdc_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( + gcdc_version.CreateVersionRequest(), + parent='parent_value', + version=gcdc_version.Version(name='name_value'), + ) + + +def test_update_version(transport: str = 'grpc', request_type=gcdc_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 = gcdc_version.Version( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_version.Version.State.RUNNING, + ) + response = client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_version.Version) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_version.Version.State.RUNNING + + +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] == gcdc_version.UpdateVersionRequest() + + +@pytest.mark.asyncio +async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_version.Version( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_version.Version.State.RUNNING, + )) + response = await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_version.Version) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_version.Version.State.RUNNING + + +@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 = gcdc_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = gcdc_version.Version() + client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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 = gcdc_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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 = gcdc_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_version( + version=gcdc_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].version == gcdc_version.Version(name='name_value') + assert args[0].update_mask == field_mask_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( + gcdc_version.UpdateVersionRequest(), + version=gcdc_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 = gcdc_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( + gcdc_version.UpdateVersionRequest(), + version=gcdc_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_load_version(transport: str = 'grpc', request_type=version.LoadVersionRequest): + 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.load_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.load_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.LoadVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_load_version_from_dict(): + test_load_version(request_type=dict) + + +def test_load_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_version), + '__call__') as call: + client.load_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.LoadVersionRequest() + + +@pytest.mark.asyncio +async def test_load_version_async(transport: str = 'grpc_asyncio', request_type=version.LoadVersionRequest): + 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.load_version), + '__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.load_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.LoadVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_load_version_async_from_dict(): + await test_load_version_async(request_type=dict) + + +def test_load_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.LoadVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.load_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_load_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.LoadVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.load_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_load_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.load_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.load_version( + name='name_value', + ) + + # Establish that the 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_load_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.load_version( + version.LoadVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_load_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.load_version), + '__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.load_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_load_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.load_version( + version.LoadVersionRequest(), + 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.dialogflowcx_v3.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', + 'load_version', + ) + 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_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.dialogflowcx_v3.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_versions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + 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.dialogflowcx_v3.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_versions_grpc_lro_client(): + client = VersionsClient( + 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_versions_grpc_lro_async_client(): + client = VersionsAsyncClient( + 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_version_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + version = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + actual = VersionsClient.version_path(project, location, agent, flow, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "flow": "winkle", + "version": "nautilus", + } + 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 = "scallop" + 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": "abalone", + } + 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 = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = VersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + 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 = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + 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 = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = VersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + 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": "winkle", + "location": "nautilus", + } + 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/v3/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py new file mode 100644 index 00000000..d46cba9b --- /dev/null +++ b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py @@ -0,0 +1,2409 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.webhooks import WebhooksAsyncClient +from google.cloud.dialogflowcx_v3.services.webhooks import WebhooksClient +from google.cloud.dialogflowcx_v3.services.webhooks import pagers +from google.cloud.dialogflowcx_v3.services.webhooks import transports +from google.cloud.dialogflowcx_v3.services.webhooks.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3.services.webhooks.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3.types import webhook +from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # 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(): + 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 WebhooksClient._get_default_mtls_endpoint(None) is None + assert WebhooksClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WebhooksClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WebhooksClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WebhooksClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WebhooksClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + WebhooksClient, + WebhooksAsyncClient, +]) +def test_webhooks_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", [ + WebhooksClient, + WebhooksAsyncClient, +]) +def test_webhooks_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_webhooks_client_get_transport_class(): + transport = WebhooksClient.get_transport_class() + available_transports = [ + transports.WebhooksGrpcTransport, + ] + assert transport in available_transports + + transport = WebhooksClient.get_transport_class("grpc") + assert transport == transports.WebhooksGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), + (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(WebhooksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksClient)) +@mock.patch.object(WebhooksAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksAsyncClient)) +def test_webhooks_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(WebhooksClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=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(WebhooksClient, '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", [ + (WebhooksClient, transports.WebhooksGrpcTransport, "grpc", "true"), + (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WebhooksClient, transports.WebhooksGrpcTransport, "grpc", "false"), + (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(WebhooksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksClient)) +@mock.patch.object(WebhooksAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_webhooks_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", [ + (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), + (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_webhooks_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", [ + (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), + (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_webhooks_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_webhooks_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WebhooksClient( + 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_webhooks(transport: str = 'grpc', request_type=webhook.ListWebhooksRequest): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhooks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.ListWebhooksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_webhooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.ListWebhooksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWebhooksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_webhooks_from_dict(): + test_list_webhooks(request_type=dict) + + +def test_list_webhooks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebhooksClient( + credentials=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_webhooks), + '__call__') as call: + client.list_webhooks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.ListWebhooksRequest() + + +@pytest.mark.asyncio +async def test_list_webhooks_async(transport: str = 'grpc_asyncio', request_type=webhook.ListWebhooksRequest): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhooks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_webhooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.ListWebhooksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWebhooksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_webhooks_async_from_dict(): + await test_list_webhooks_async(request_type=dict) + + +def test_list_webhooks_field_headers(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.ListWebhooksRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + call.return_value = webhook.ListWebhooksResponse() + client.list_webhooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_webhooks_field_headers_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.ListWebhooksRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse()) + await client.list_webhooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_webhooks_flattened(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.ListWebhooksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_webhooks( + parent='parent_value', + ) + + # Establish that the 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_webhooks_flattened_error(): + client = WebhooksClient( + credentials=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_webhooks( + webhook.ListWebhooksRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_webhooks_flattened_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.ListWebhooksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_webhooks( + 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_webhooks_flattened_error_async(): + client = WebhooksAsyncClient( + credentials=ga_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_webhooks( + webhook.ListWebhooksRequest(), + parent='parent_value', + ) + + +def test_list_webhooks_pager(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + webhook.Webhook(), + ], + next_page_token='abc', + ), + webhook.ListWebhooksResponse( + webhooks=[], + next_page_token='def', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + ], + next_page_token='ghi', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_webhooks(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, webhook.Webhook) + for i in results) + +def test_list_webhooks_pages(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + webhook.Webhook(), + ], + next_page_token='abc', + ), + webhook.ListWebhooksResponse( + webhooks=[], + next_page_token='def', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + ], + next_page_token='ghi', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + ], + ), + RuntimeError, + ) + pages = list(client.list_webhooks(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_webhooks_async_pager(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + webhook.Webhook(), + ], + next_page_token='abc', + ), + webhook.ListWebhooksResponse( + webhooks=[], + next_page_token='def', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + ], + next_page_token='ghi', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_webhooks(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, webhook.Webhook) + for i in responses) + +@pytest.mark.asyncio +async def test_list_webhooks_async_pages(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + webhook.Webhook(), + ], + next_page_token='abc', + ), + webhook.ListWebhooksResponse( + webhooks=[], + next_page_token='def', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + ], + next_page_token='ghi', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_webhooks(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_webhook(transport: str = 'grpc', request_type=webhook.GetWebhookRequest): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + generic_web_service=webhook.Webhook.GenericWebService(uri='uri_value'), + ) + response = client.get_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.GetWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +def test_get_webhook_from_dict(): + test_get_webhook(request_type=dict) + + +def test_get_webhook_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebhooksClient( + credentials=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_webhook), + '__call__') as call: + client.get_webhook() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.GetWebhookRequest() + + +@pytest.mark.asyncio +async def test_get_webhook_async(transport: str = 'grpc_asyncio', request_type=webhook.GetWebhookRequest): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + )) + response = await client.get_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.GetWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_get_webhook_async_from_dict(): + await test_get_webhook_async(request_type=dict) + + +def test_get_webhook_field_headers(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.GetWebhookRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_webhook), + '__call__') as call: + call.return_value = webhook.Webhook() + client.get_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_webhook_field_headers_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.GetWebhookRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_webhook), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook()) + await client.get_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_webhook_flattened(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.Webhook() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_webhook( + name='name_value', + ) + + # Establish that the 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_webhook_flattened_error(): + client = WebhooksClient( + credentials=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_webhook( + webhook.GetWebhookRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_webhook_flattened_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.Webhook() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_webhook( + 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_webhook_flattened_error_async(): + client = WebhooksAsyncClient( + credentials=ga_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_webhook( + webhook.GetWebhookRequest(), + name='name_value', + ) + + +def test_create_webhook(transport: str = 'grpc', request_type=gcdc_webhook.CreateWebhookRequest): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri='uri_value'), + ) + response = client.create_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.CreateWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +def test_create_webhook_from_dict(): + test_create_webhook(request_type=dict) + + +def test_create_webhook_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebhooksClient( + credentials=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_webhook), + '__call__') as call: + client.create_webhook() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.CreateWebhookRequest() + + +@pytest.mark.asyncio +async def test_create_webhook_async(transport: str = 'grpc_asyncio', request_type=gcdc_webhook.CreateWebhookRequest): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + )) + response = await client.create_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.CreateWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_create_webhook_async_from_dict(): + await test_create_webhook_async(request_type=dict) + + +def test_create_webhook_field_headers(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_webhook.CreateWebhookRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_webhook), + '__call__') as call: + call.return_value = gcdc_webhook.Webhook() + client.create_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_webhook_field_headers_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_webhook.CreateWebhookRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_webhook), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) + await client.create_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_webhook_flattened(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_webhook( + parent='parent_value', + webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') + + +def test_create_webhook_flattened_error(): + client = WebhooksClient( + credentials=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_webhook( + gcdc_webhook.CreateWebhookRequest(), + parent='parent_value', + webhook=gcdc_webhook.Webhook(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_webhook_flattened_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_webhook( + parent='parent_value', + webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') + + +@pytest.mark.asyncio +async def test_create_webhook_flattened_error_async(): + client = WebhooksAsyncClient( + credentials=ga_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_webhook( + gcdc_webhook.CreateWebhookRequest(), + parent='parent_value', + webhook=gcdc_webhook.Webhook(name='name_value'), + ) + + +def test_update_webhook(transport: str = 'grpc', request_type=gcdc_webhook.UpdateWebhookRequest): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri='uri_value'), + ) + response = client.update_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.UpdateWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +def test_update_webhook_from_dict(): + test_update_webhook(request_type=dict) + + +def test_update_webhook_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebhooksClient( + credentials=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_webhook), + '__call__') as call: + client.update_webhook() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.UpdateWebhookRequest() + + +@pytest.mark.asyncio +async def test_update_webhook_async(transport: str = 'grpc_asyncio', request_type=gcdc_webhook.UpdateWebhookRequest): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + )) + response = await client.update_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.UpdateWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_update_webhook_async_from_dict(): + await test_update_webhook_async(request_type=dict) + + +def test_update_webhook_field_headers(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_webhook.UpdateWebhookRequest() + + request.webhook.name = 'webhook.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_webhook), + '__call__') as call: + call.return_value = gcdc_webhook.Webhook() + client.update_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'webhook.name=webhook.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_webhook_field_headers_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_webhook.UpdateWebhookRequest() + + request.webhook.name = 'webhook.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_webhook), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) + await client.update_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'webhook.name=webhook.name/value', + ) in kw['metadata'] + + +def test_update_webhook_flattened(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_webhook( + webhook=gcdc_webhook.Webhook(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].webhook == gcdc_webhook.Webhook(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_webhook_flattened_error(): + client = WebhooksClient( + credentials=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_webhook( + gcdc_webhook.UpdateWebhookRequest(), + webhook=gcdc_webhook.Webhook(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_webhook_flattened_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_webhook( + webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_webhook_flattened_error_async(): + client = WebhooksAsyncClient( + credentials=ga_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_webhook( + gcdc_webhook.UpdateWebhookRequest(), + webhook=gcdc_webhook.Webhook(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_webhook(transport: str = 'grpc', request_type=webhook.DeleteWebhookRequest): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.DeleteWebhookRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_webhook_from_dict(): + test_delete_webhook(request_type=dict) + + +def test_delete_webhook_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebhooksClient( + credentials=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_webhook), + '__call__') as call: + client.delete_webhook() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.DeleteWebhookRequest() + + +@pytest.mark.asyncio +async def test_delete_webhook_async(transport: str = 'grpc_asyncio', request_type=webhook.DeleteWebhookRequest): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.DeleteWebhookRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_webhook_async_from_dict(): + await test_delete_webhook_async(request_type=dict) + + +def test_delete_webhook_field_headers(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.DeleteWebhookRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_webhook), + '__call__') as call: + call.return_value = None + client.delete_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_webhook_field_headers_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.DeleteWebhookRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_webhook), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_webhook_flattened(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_webhook( + name='name_value', + ) + + # Establish that the 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_webhook_flattened_error(): + client = WebhooksClient( + credentials=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_webhook( + webhook.DeleteWebhookRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_webhook_flattened_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_webhook), + '__call__') as call: + # 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_webhook( + 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_webhook_flattened_error_async(): + client = WebhooksAsyncClient( + credentials=ga_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_webhook( + webhook.DeleteWebhookRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebhooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebhooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebhooksClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebhooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebhooksClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebhooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebhooksClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebhooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebhooksGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WebhooksGrpcTransport, + transports.WebhooksGrpcAsyncIOTransport, +]) +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 = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebhooksGrpcTransport, + ) + +def test_webhooks_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebhooksTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_webhooks_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WebhooksTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_webhooks', + 'get_webhook', + 'create_webhook', + 'update_webhook', + 'delete_webhook', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_webhooks_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebhooksTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_webhooks_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebhooksTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_webhooks_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebhooksTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_webhooks_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WebhooksClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_webhooks_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WebhooksClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebhooksGrpcTransport, + transports.WebhooksGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_webhooks_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebhooksGrpcTransport, + transports.WebhooksGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_webhooks_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_webhooks_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_webhooks_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_webhooks_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) +def test_webhooks_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = 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_webhooks_host_no_port(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_webhooks_host_with_port(): + client = WebhooksClient( + 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_webhooks_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebhooksGrpcTransport( + 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_webhooks_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebhooksGrpcAsyncIOTransport( + 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.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) +def test_webhooks_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.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) +def test_webhooks_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_service_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + actual = WebhooksClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "namespace": "cuttlefish", + "service": "mussel", + } + path = WebhooksClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_service_path(path) + assert expected == actual + +def test_webhook_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = WebhooksClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", + } + path = WebhooksClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WebhooksClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = WebhooksClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = WebhooksClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = WebhooksClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WebhooksClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = WebhooksClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = WebhooksClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = WebhooksClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.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 = WebhooksClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = WebhooksClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.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.WebhooksTransport, '_prep_wrapped_messages') as prep: + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WebhooksTransport, '_prep_wrapped_messages') as prep: + transport_class = WebhooksClient.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/v3beta1/MANIFEST.in b/owl-bot-staging/v3beta1/MANIFEST.in new file mode 100644 index 00000000..8a0b3570 --- /dev/null +++ b/owl-bot-staging/v3beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/dialogflowcx *.py +recursive-include google/cloud/dialogflowcx_v3beta1 *.py diff --git a/owl-bot-staging/v3beta1/README.rst b/owl-bot-staging/v3beta1/README.rst new file mode 100644 index 00000000..bfe57a44 --- /dev/null +++ b/owl-bot-staging/v3beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Dialogflowcx 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 Dialogflowcx 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/v3beta1/docs/conf.py b/owl-bot-staging/v3beta1/docs/conf.py new file mode 100644 index 00000000..814121cd --- /dev/null +++ b/owl-bot-staging/v3beta1/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-dialogflowcx 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-dialogflowcx" +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-dialogflowcx-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-dialogflowcx.tex", + u"google-cloud-dialogflowcx 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-dialogflowcx", + u"Google Cloud Dialogflowcx 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-dialogflowcx", + u"google-cloud-dialogflowcx Documentation", + author, + "google-cloud-dialogflowcx", + "GAPIC library for Google Cloud Dialogflowcx 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/v3beta1/docs/dialogflowcx_v3beta1/agents.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/agents.rst new file mode 100644 index 00000000..511ac6f9 --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/agents.rst @@ -0,0 +1,10 @@ +Agents +------------------------ + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.agents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.agents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/entity_types.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/entity_types.rst new file mode 100644 index 00000000..3878a96e --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/entity_types.rst @@ -0,0 +1,10 @@ +EntityTypes +----------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.entity_types + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.entity_types.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/environments.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/environments.rst new file mode 100644 index 00000000..0e31d34d --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/environments.rst @@ -0,0 +1,10 @@ +Environments +------------------------------ + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.environments + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.environments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/experiments.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/experiments.rst new file mode 100644 index 00000000..5c185e4f --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/experiments.rst @@ -0,0 +1,10 @@ +Experiments +----------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.experiments + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.experiments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/flows.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/flows.rst new file mode 100644 index 00000000..0183ff3b --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/flows.rst @@ -0,0 +1,10 @@ +Flows +----------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.flows + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.flows.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/intents.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/intents.rst new file mode 100644 index 00000000..3bf9d37c --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/intents.rst @@ -0,0 +1,10 @@ +Intents +------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.intents + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.intents.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/pages.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/pages.rst new file mode 100644 index 00000000..be3f1b16 --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/pages.rst @@ -0,0 +1,10 @@ +Pages +----------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.pages + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.pages.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/security_settings_service.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/security_settings_service.rst new file mode 100644 index 00000000..0489568a --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/security_settings_service.rst @@ -0,0 +1,10 @@ +SecuritySettingsService +----------------------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.security_settings_service + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.security_settings_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/services.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/services.rst new file mode 100644 index 00000000..03f147db --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/services.rst @@ -0,0 +1,19 @@ +Services for Google Cloud Dialogflowcx v3beta1 API +================================================== +.. toctree:: + :maxdepth: 2 + + agents + entity_types + environments + experiments + flows + intents + pages + security_settings_service + session_entity_types + sessions + test_cases + transition_route_groups + versions + webhooks diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/session_entity_types.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/session_entity_types.rst new file mode 100644 index 00000000..a6248835 --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/session_entity_types.rst @@ -0,0 +1,10 @@ +SessionEntityTypes +------------------------------------ + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.session_entity_types + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.session_entity_types.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/sessions.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/sessions.rst new file mode 100644 index 00000000..3f792bf8 --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/sessions.rst @@ -0,0 +1,6 @@ +Sessions +-------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.sessions + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/test_cases.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/test_cases.rst new file mode 100644 index 00000000..a212f0b4 --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/test_cases.rst @@ -0,0 +1,10 @@ +TestCases +--------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.test_cases + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/transition_route_groups.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/transition_route_groups.rst new file mode 100644 index 00000000..9b29ddf9 --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/transition_route_groups.rst @@ -0,0 +1,10 @@ +TransitionRouteGroups +--------------------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.transition_route_groups + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/types.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/types.rst new file mode 100644 index 00000000..a7388b27 --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Dialogflowcx v3beta1 API +=============================================== + +.. automodule:: google.cloud.dialogflowcx_v3beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/versions.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/versions.rst new file mode 100644 index 00000000..6617fb66 --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/versions.rst @@ -0,0 +1,10 @@ +Versions +-------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.versions + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.versions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/webhooks.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/webhooks.rst new file mode 100644 index 00000000..4fa96e0f --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/webhooks.rst @@ -0,0 +1,10 @@ +Webhooks +-------------------------- + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.webhooks + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflowcx_v3beta1.services.webhooks.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/index.rst b/owl-bot-staging/v3beta1/docs/index.rst new file mode 100644 index 00000000..7944398b --- /dev/null +++ b/owl-bot-staging/v3beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + dialogflowcx_v3beta1/services + dialogflowcx_v3beta1/types diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/__init__.py new file mode 100644 index 00000000..8e0cebda --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/__init__.py @@ -0,0 +1,451 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.agents.client import AgentsClient +from google.cloud.dialogflowcx_v3beta1.services.agents.async_client import AgentsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.entity_types.client import EntityTypesClient +from google.cloud.dialogflowcx_v3beta1.services.entity_types.async_client import EntityTypesAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.environments.client import EnvironmentsClient +from google.cloud.dialogflowcx_v3beta1.services.environments.async_client import EnvironmentsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.experiments.client import ExperimentsClient +from google.cloud.dialogflowcx_v3beta1.services.experiments.async_client import ExperimentsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.flows.client import FlowsClient +from google.cloud.dialogflowcx_v3beta1.services.flows.async_client import FlowsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.intents.client import IntentsClient +from google.cloud.dialogflowcx_v3beta1.services.intents.async_client import IntentsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.pages.client import PagesClient +from google.cloud.dialogflowcx_v3beta1.services.pages.async_client import PagesAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service.client import SecuritySettingsServiceClient +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service.async_client import SecuritySettingsServiceAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.session_entity_types.client import SessionEntityTypesClient +from google.cloud.dialogflowcx_v3beta1.services.session_entity_types.async_client import SessionEntityTypesAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.sessions.client import SessionsClient +from google.cloud.dialogflowcx_v3beta1.services.sessions.async_client import SessionsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.test_cases.client import TestCasesClient +from google.cloud.dialogflowcx_v3beta1.services.test_cases.async_client import TestCasesAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.client import TransitionRouteGroupsClient +from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.async_client import TransitionRouteGroupsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.versions.client import VersionsClient +from google.cloud.dialogflowcx_v3beta1.services.versions.async_client import VersionsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.webhooks.client import WebhooksClient +from google.cloud.dialogflowcx_v3beta1.services.webhooks.async_client import WebhooksAsyncClient + +from google.cloud.dialogflowcx_v3beta1.types.agent import Agent +from google.cloud.dialogflowcx_v3beta1.types.agent import AgentValidationResult +from google.cloud.dialogflowcx_v3beta1.types.agent import CreateAgentRequest +from google.cloud.dialogflowcx_v3beta1.types.agent import DeleteAgentRequest +from google.cloud.dialogflowcx_v3beta1.types.agent import ExportAgentRequest +from google.cloud.dialogflowcx_v3beta1.types.agent import ExportAgentResponse +from google.cloud.dialogflowcx_v3beta1.types.agent import GetAgentRequest +from google.cloud.dialogflowcx_v3beta1.types.agent import GetAgentValidationResultRequest +from google.cloud.dialogflowcx_v3beta1.types.agent import ListAgentsRequest +from google.cloud.dialogflowcx_v3beta1.types.agent import ListAgentsResponse +from google.cloud.dialogflowcx_v3beta1.types.agent import RestoreAgentRequest +from google.cloud.dialogflowcx_v3beta1.types.agent import SpeechToTextSettings +from google.cloud.dialogflowcx_v3beta1.types.agent import UpdateAgentRequest +from google.cloud.dialogflowcx_v3beta1.types.agent import ValidateAgentRequest +from google.cloud.dialogflowcx_v3beta1.types.audio_config import InputAudioConfig +from google.cloud.dialogflowcx_v3beta1.types.audio_config import OutputAudioConfig +from google.cloud.dialogflowcx_v3beta1.types.audio_config import SpeechWordInfo +from google.cloud.dialogflowcx_v3beta1.types.audio_config import SynthesizeSpeechConfig +from google.cloud.dialogflowcx_v3beta1.types.audio_config import VoiceSelectionParams +from google.cloud.dialogflowcx_v3beta1.types.audio_config import AudioEncoding +from google.cloud.dialogflowcx_v3beta1.types.audio_config import OutputAudioEncoding +from google.cloud.dialogflowcx_v3beta1.types.audio_config import SpeechModelVariant +from google.cloud.dialogflowcx_v3beta1.types.audio_config import SsmlVoiceGender +from google.cloud.dialogflowcx_v3beta1.types.entity_type import CreateEntityTypeRequest +from google.cloud.dialogflowcx_v3beta1.types.entity_type import DeleteEntityTypeRequest +from google.cloud.dialogflowcx_v3beta1.types.entity_type import EntityType +from google.cloud.dialogflowcx_v3beta1.types.entity_type import GetEntityTypeRequest +from google.cloud.dialogflowcx_v3beta1.types.entity_type import ListEntityTypesRequest +from google.cloud.dialogflowcx_v3beta1.types.entity_type import ListEntityTypesResponse +from google.cloud.dialogflowcx_v3beta1.types.entity_type import UpdateEntityTypeRequest +from google.cloud.dialogflowcx_v3beta1.types.environment import ContinuousTestResult +from google.cloud.dialogflowcx_v3beta1.types.environment import CreateEnvironmentRequest +from google.cloud.dialogflowcx_v3beta1.types.environment import DeleteEnvironmentRequest +from google.cloud.dialogflowcx_v3beta1.types.environment import Environment +from google.cloud.dialogflowcx_v3beta1.types.environment import GetEnvironmentRequest +from google.cloud.dialogflowcx_v3beta1.types.environment import ListContinuousTestResultsRequest +from google.cloud.dialogflowcx_v3beta1.types.environment import ListContinuousTestResultsResponse +from google.cloud.dialogflowcx_v3beta1.types.environment import ListEnvironmentsRequest +from google.cloud.dialogflowcx_v3beta1.types.environment import ListEnvironmentsResponse +from google.cloud.dialogflowcx_v3beta1.types.environment import LookupEnvironmentHistoryRequest +from google.cloud.dialogflowcx_v3beta1.types.environment import LookupEnvironmentHistoryResponse +from google.cloud.dialogflowcx_v3beta1.types.environment import RunContinuousTestMetadata +from google.cloud.dialogflowcx_v3beta1.types.environment import RunContinuousTestRequest +from google.cloud.dialogflowcx_v3beta1.types.environment import RunContinuousTestResponse +from google.cloud.dialogflowcx_v3beta1.types.environment import UpdateEnvironmentRequest +from google.cloud.dialogflowcx_v3beta1.types.experiment import CreateExperimentRequest +from google.cloud.dialogflowcx_v3beta1.types.experiment import DeleteExperimentRequest +from google.cloud.dialogflowcx_v3beta1.types.experiment import Experiment +from google.cloud.dialogflowcx_v3beta1.types.experiment import GetExperimentRequest +from google.cloud.dialogflowcx_v3beta1.types.experiment import ListExperimentsRequest +from google.cloud.dialogflowcx_v3beta1.types.experiment import ListExperimentsResponse +from google.cloud.dialogflowcx_v3beta1.types.experiment import StartExperimentRequest +from google.cloud.dialogflowcx_v3beta1.types.experiment import StopExperimentRequest +from google.cloud.dialogflowcx_v3beta1.types.experiment import UpdateExperimentRequest +from google.cloud.dialogflowcx_v3beta1.types.experiment import VariantsHistory +from google.cloud.dialogflowcx_v3beta1.types.experiment import VersionVariants +from google.cloud.dialogflowcx_v3beta1.types.flow import CreateFlowRequest +from google.cloud.dialogflowcx_v3beta1.types.flow import DeleteFlowRequest +from google.cloud.dialogflowcx_v3beta1.types.flow import ExportFlowRequest +from google.cloud.dialogflowcx_v3beta1.types.flow import ExportFlowResponse +from google.cloud.dialogflowcx_v3beta1.types.flow import Flow +from google.cloud.dialogflowcx_v3beta1.types.flow import FlowValidationResult +from google.cloud.dialogflowcx_v3beta1.types.flow import GetFlowRequest +from google.cloud.dialogflowcx_v3beta1.types.flow import GetFlowValidationResultRequest +from google.cloud.dialogflowcx_v3beta1.types.flow import ImportFlowRequest +from google.cloud.dialogflowcx_v3beta1.types.flow import ImportFlowResponse +from google.cloud.dialogflowcx_v3beta1.types.flow import ListFlowsRequest +from google.cloud.dialogflowcx_v3beta1.types.flow import ListFlowsResponse +from google.cloud.dialogflowcx_v3beta1.types.flow import NluSettings +from google.cloud.dialogflowcx_v3beta1.types.flow import TrainFlowRequest +from google.cloud.dialogflowcx_v3beta1.types.flow import UpdateFlowRequest +from google.cloud.dialogflowcx_v3beta1.types.flow import ValidateFlowRequest +from google.cloud.dialogflowcx_v3beta1.types.fulfillment import Fulfillment +from google.cloud.dialogflowcx_v3beta1.types.intent import CreateIntentRequest +from google.cloud.dialogflowcx_v3beta1.types.intent import DeleteIntentRequest +from google.cloud.dialogflowcx_v3beta1.types.intent import GetIntentRequest +from google.cloud.dialogflowcx_v3beta1.types.intent import Intent +from google.cloud.dialogflowcx_v3beta1.types.intent import ListIntentsRequest +from google.cloud.dialogflowcx_v3beta1.types.intent import ListIntentsResponse +from google.cloud.dialogflowcx_v3beta1.types.intent import UpdateIntentRequest +from google.cloud.dialogflowcx_v3beta1.types.intent import IntentView +from google.cloud.dialogflowcx_v3beta1.types.page import CreatePageRequest +from google.cloud.dialogflowcx_v3beta1.types.page import DeletePageRequest +from google.cloud.dialogflowcx_v3beta1.types.page import EventHandler +from google.cloud.dialogflowcx_v3beta1.types.page import Form +from google.cloud.dialogflowcx_v3beta1.types.page import GetPageRequest +from google.cloud.dialogflowcx_v3beta1.types.page import ListPagesRequest +from google.cloud.dialogflowcx_v3beta1.types.page import ListPagesResponse +from google.cloud.dialogflowcx_v3beta1.types.page import Page +from google.cloud.dialogflowcx_v3beta1.types.page import TransitionRoute +from google.cloud.dialogflowcx_v3beta1.types.page import UpdatePageRequest +from google.cloud.dialogflowcx_v3beta1.types.response_message import ResponseMessage +from google.cloud.dialogflowcx_v3beta1.types.security_settings import CreateSecuritySettingsRequest +from google.cloud.dialogflowcx_v3beta1.types.security_settings import DeleteSecuritySettingsRequest +from google.cloud.dialogflowcx_v3beta1.types.security_settings import GetSecuritySettingsRequest +from google.cloud.dialogflowcx_v3beta1.types.security_settings import ListSecuritySettingsRequest +from google.cloud.dialogflowcx_v3beta1.types.security_settings import ListSecuritySettingsResponse +from google.cloud.dialogflowcx_v3beta1.types.security_settings import SecuritySettings +from google.cloud.dialogflowcx_v3beta1.types.security_settings import UpdateSecuritySettingsRequest +from google.cloud.dialogflowcx_v3beta1.types.session import AudioInput +from google.cloud.dialogflowcx_v3beta1.types.session import DetectIntentRequest +from google.cloud.dialogflowcx_v3beta1.types.session import DetectIntentResponse +from google.cloud.dialogflowcx_v3beta1.types.session import DtmfInput +from google.cloud.dialogflowcx_v3beta1.types.session import EventInput +from google.cloud.dialogflowcx_v3beta1.types.session import FulfillIntentRequest +from google.cloud.dialogflowcx_v3beta1.types.session import FulfillIntentResponse +from google.cloud.dialogflowcx_v3beta1.types.session import IntentInput +from google.cloud.dialogflowcx_v3beta1.types.session import Match +from google.cloud.dialogflowcx_v3beta1.types.session import MatchIntentRequest +from google.cloud.dialogflowcx_v3beta1.types.session import MatchIntentResponse +from google.cloud.dialogflowcx_v3beta1.types.session import QueryInput +from google.cloud.dialogflowcx_v3beta1.types.session import QueryParameters +from google.cloud.dialogflowcx_v3beta1.types.session import QueryResult +from google.cloud.dialogflowcx_v3beta1.types.session import SentimentAnalysisResult +from google.cloud.dialogflowcx_v3beta1.types.session import StreamingDetectIntentRequest +from google.cloud.dialogflowcx_v3beta1.types.session import StreamingDetectIntentResponse +from google.cloud.dialogflowcx_v3beta1.types.session import StreamingRecognitionResult +from google.cloud.dialogflowcx_v3beta1.types.session import TextInput +from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import CreateSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import DeleteSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import GetSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import ListSessionEntityTypesRequest +from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import ListSessionEntityTypesResponse +from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import SessionEntityType +from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import UpdateSessionEntityTypeRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import BatchDeleteTestCasesRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import BatchRunTestCasesMetadata +from google.cloud.dialogflowcx_v3beta1.types.test_case import BatchRunTestCasesRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import BatchRunTestCasesResponse +from google.cloud.dialogflowcx_v3beta1.types.test_case import CalculateCoverageRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import CalculateCoverageResponse +from google.cloud.dialogflowcx_v3beta1.types.test_case import ConversationTurn +from google.cloud.dialogflowcx_v3beta1.types.test_case import CreateTestCaseRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import ExportTestCasesMetadata +from google.cloud.dialogflowcx_v3beta1.types.test_case import ExportTestCasesRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import ExportTestCasesResponse +from google.cloud.dialogflowcx_v3beta1.types.test_case import GetTestCaseRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import GetTestCaseResultRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import ImportTestCasesMetadata +from google.cloud.dialogflowcx_v3beta1.types.test_case import ImportTestCasesRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import ImportTestCasesResponse +from google.cloud.dialogflowcx_v3beta1.types.test_case import IntentCoverage +from google.cloud.dialogflowcx_v3beta1.types.test_case import ListTestCaseResultsRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import ListTestCaseResultsResponse +from google.cloud.dialogflowcx_v3beta1.types.test_case import ListTestCasesRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import ListTestCasesResponse +from google.cloud.dialogflowcx_v3beta1.types.test_case import RunTestCaseMetadata +from google.cloud.dialogflowcx_v3beta1.types.test_case import RunTestCaseRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import RunTestCaseResponse +from google.cloud.dialogflowcx_v3beta1.types.test_case import TestCase +from google.cloud.dialogflowcx_v3beta1.types.test_case import TestCaseError +from google.cloud.dialogflowcx_v3beta1.types.test_case import TestCaseResult +from google.cloud.dialogflowcx_v3beta1.types.test_case import TestConfig +from google.cloud.dialogflowcx_v3beta1.types.test_case import TestError +from google.cloud.dialogflowcx_v3beta1.types.test_case import TestRunDifference +from google.cloud.dialogflowcx_v3beta1.types.test_case import TransitionCoverage +from google.cloud.dialogflowcx_v3beta1.types.test_case import TransitionRouteGroupCoverage +from google.cloud.dialogflowcx_v3beta1.types.test_case import UpdateTestCaseRequest +from google.cloud.dialogflowcx_v3beta1.types.test_case import TestResult +from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import CreateTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import DeleteTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import GetTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import ListTransitionRouteGroupsRequest +from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import ListTransitionRouteGroupsResponse +from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import TransitionRouteGroup +from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import UpdateTransitionRouteGroupRequest +from google.cloud.dialogflowcx_v3beta1.types.validation_message import ResourceName +from google.cloud.dialogflowcx_v3beta1.types.validation_message import ValidationMessage +from google.cloud.dialogflowcx_v3beta1.types.version import CreateVersionOperationMetadata +from google.cloud.dialogflowcx_v3beta1.types.version import CreateVersionRequest +from google.cloud.dialogflowcx_v3beta1.types.version import DeleteVersionRequest +from google.cloud.dialogflowcx_v3beta1.types.version import GetVersionRequest +from google.cloud.dialogflowcx_v3beta1.types.version import ListVersionsRequest +from google.cloud.dialogflowcx_v3beta1.types.version import ListVersionsResponse +from google.cloud.dialogflowcx_v3beta1.types.version import LoadVersionRequest +from google.cloud.dialogflowcx_v3beta1.types.version import UpdateVersionRequest +from google.cloud.dialogflowcx_v3beta1.types.version import Version +from google.cloud.dialogflowcx_v3beta1.types.webhook import CreateWebhookRequest +from google.cloud.dialogflowcx_v3beta1.types.webhook import DeleteWebhookRequest +from google.cloud.dialogflowcx_v3beta1.types.webhook import GetWebhookRequest +from google.cloud.dialogflowcx_v3beta1.types.webhook import ListWebhooksRequest +from google.cloud.dialogflowcx_v3beta1.types.webhook import ListWebhooksResponse +from google.cloud.dialogflowcx_v3beta1.types.webhook import PageInfo +from google.cloud.dialogflowcx_v3beta1.types.webhook import SessionInfo +from google.cloud.dialogflowcx_v3beta1.types.webhook import UpdateWebhookRequest +from google.cloud.dialogflowcx_v3beta1.types.webhook import Webhook +from google.cloud.dialogflowcx_v3beta1.types.webhook import WebhookRequest +from google.cloud.dialogflowcx_v3beta1.types.webhook import WebhookResponse + +__all__ = ('AgentsClient', + 'AgentsAsyncClient', + 'EntityTypesClient', + 'EntityTypesAsyncClient', + 'EnvironmentsClient', + 'EnvironmentsAsyncClient', + 'ExperimentsClient', + 'ExperimentsAsyncClient', + 'FlowsClient', + 'FlowsAsyncClient', + 'IntentsClient', + 'IntentsAsyncClient', + 'PagesClient', + 'PagesAsyncClient', + 'SecuritySettingsServiceClient', + 'SecuritySettingsServiceAsyncClient', + 'SessionEntityTypesClient', + 'SessionEntityTypesAsyncClient', + 'SessionsClient', + 'SessionsAsyncClient', + 'TestCasesClient', + 'TestCasesAsyncClient', + 'TransitionRouteGroupsClient', + 'TransitionRouteGroupsAsyncClient', + 'VersionsClient', + 'VersionsAsyncClient', + 'WebhooksClient', + 'WebhooksAsyncClient', + 'Agent', + 'AgentValidationResult', + 'CreateAgentRequest', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'GetAgentRequest', + 'GetAgentValidationResultRequest', + 'ListAgentsRequest', + 'ListAgentsResponse', + 'RestoreAgentRequest', + 'SpeechToTextSettings', + 'UpdateAgentRequest', + 'ValidateAgentRequest', + 'InputAudioConfig', + 'OutputAudioConfig', + 'SpeechWordInfo', + 'SynthesizeSpeechConfig', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'ContinuousTestResult', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'Environment', + 'GetEnvironmentRequest', + 'ListContinuousTestResultsRequest', + 'ListContinuousTestResultsResponse', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LookupEnvironmentHistoryRequest', + 'LookupEnvironmentHistoryResponse', + 'RunContinuousTestMetadata', + 'RunContinuousTestRequest', + 'RunContinuousTestResponse', + 'UpdateEnvironmentRequest', + 'CreateExperimentRequest', + 'DeleteExperimentRequest', + 'Experiment', + 'GetExperimentRequest', + 'ListExperimentsRequest', + 'ListExperimentsResponse', + 'StartExperimentRequest', + 'StopExperimentRequest', + 'UpdateExperimentRequest', + 'VariantsHistory', + 'VersionVariants', + 'CreateFlowRequest', + 'DeleteFlowRequest', + 'ExportFlowRequest', + 'ExportFlowResponse', + 'Flow', + 'FlowValidationResult', + 'GetFlowRequest', + 'GetFlowValidationResultRequest', + 'ImportFlowRequest', + 'ImportFlowResponse', + 'ListFlowsRequest', + 'ListFlowsResponse', + 'NluSettings', + 'TrainFlowRequest', + 'UpdateFlowRequest', + 'ValidateFlowRequest', + 'Fulfillment', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreatePageRequest', + 'DeletePageRequest', + 'EventHandler', + 'Form', + 'GetPageRequest', + 'ListPagesRequest', + 'ListPagesResponse', + 'Page', + 'TransitionRoute', + 'UpdatePageRequest', + 'ResponseMessage', + 'CreateSecuritySettingsRequest', + 'DeleteSecuritySettingsRequest', + 'GetSecuritySettingsRequest', + 'ListSecuritySettingsRequest', + 'ListSecuritySettingsResponse', + 'SecuritySettings', + 'UpdateSecuritySettingsRequest', + 'AudioInput', + 'DetectIntentRequest', + 'DetectIntentResponse', + 'DtmfInput', + 'EventInput', + 'FulfillIntentRequest', + 'FulfillIntentResponse', + 'IntentInput', + 'Match', + 'MatchIntentRequest', + 'MatchIntentResponse', + 'QueryInput', + 'QueryParameters', + 'QueryResult', + 'SentimentAnalysisResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'CreateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + 'GetSessionEntityTypeRequest', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'SessionEntityType', + 'UpdateSessionEntityTypeRequest', + 'BatchDeleteTestCasesRequest', + 'BatchRunTestCasesMetadata', + 'BatchRunTestCasesRequest', + 'BatchRunTestCasesResponse', + 'CalculateCoverageRequest', + 'CalculateCoverageResponse', + 'ConversationTurn', + 'CreateTestCaseRequest', + 'ExportTestCasesMetadata', + 'ExportTestCasesRequest', + 'ExportTestCasesResponse', + 'GetTestCaseRequest', + 'GetTestCaseResultRequest', + 'ImportTestCasesMetadata', + 'ImportTestCasesRequest', + 'ImportTestCasesResponse', + 'IntentCoverage', + 'ListTestCaseResultsRequest', + 'ListTestCaseResultsResponse', + 'ListTestCasesRequest', + 'ListTestCasesResponse', + 'RunTestCaseMetadata', + 'RunTestCaseRequest', + 'RunTestCaseResponse', + 'TestCase', + 'TestCaseError', + 'TestCaseResult', + 'TestConfig', + 'TestError', + 'TestRunDifference', + 'TransitionCoverage', + 'TransitionRouteGroupCoverage', + 'UpdateTestCaseRequest', + 'TestResult', + 'CreateTransitionRouteGroupRequest', + 'DeleteTransitionRouteGroupRequest', + 'GetTransitionRouteGroupRequest', + 'ListTransitionRouteGroupsRequest', + 'ListTransitionRouteGroupsResponse', + 'TransitionRouteGroup', + 'UpdateTransitionRouteGroupRequest', + 'ResourceName', + 'ValidationMessage', + 'CreateVersionOperationMetadata', + 'CreateVersionRequest', + 'DeleteVersionRequest', + 'GetVersionRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'LoadVersionRequest', + 'UpdateVersionRequest', + 'Version', + 'CreateWebhookRequest', + 'DeleteWebhookRequest', + 'GetWebhookRequest', + 'ListWebhooksRequest', + 'ListWebhooksResponse', + 'PageInfo', + 'SessionInfo', + 'UpdateWebhookRequest', + 'Webhook', + 'WebhookRequest', + 'WebhookResponse', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/py.typed b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/py.typed new file mode 100644 index 00000000..60fdca49 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dialogflowcx package uses inline types. diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/__init__.py new file mode 100644 index 00000000..71e275f7 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/__init__.py @@ -0,0 +1,452 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient +from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.experiments import ExperimentsClient +from .services.experiments import ExperimentsAsyncClient +from .services.flows import FlowsClient +from .services.flows import FlowsAsyncClient +from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient +from .services.pages import PagesClient +from .services.pages import PagesAsyncClient +from .services.security_settings_service import SecuritySettingsServiceClient +from .services.security_settings_service import SecuritySettingsServiceAsyncClient +from .services.session_entity_types import SessionEntityTypesClient +from .services.session_entity_types import SessionEntityTypesAsyncClient +from .services.sessions import SessionsClient +from .services.sessions import SessionsAsyncClient +from .services.test_cases import TestCasesClient +from .services.test_cases import TestCasesAsyncClient +from .services.transition_route_groups import TransitionRouteGroupsClient +from .services.transition_route_groups import TransitionRouteGroupsAsyncClient +from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient +from .services.webhooks import WebhooksClient +from .services.webhooks import WebhooksAsyncClient + +from .types.agent import Agent +from .types.agent import AgentValidationResult +from .types.agent import CreateAgentRequest +from .types.agent import DeleteAgentRequest +from .types.agent import ExportAgentRequest +from .types.agent import ExportAgentResponse +from .types.agent import GetAgentRequest +from .types.agent import GetAgentValidationResultRequest +from .types.agent import ListAgentsRequest +from .types.agent import ListAgentsResponse +from .types.agent import RestoreAgentRequest +from .types.agent import SpeechToTextSettings +from .types.agent import UpdateAgentRequest +from .types.agent import ValidateAgentRequest +from .types.audio_config import InputAudioConfig +from .types.audio_config import OutputAudioConfig +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.entity_type import CreateEntityTypeRequest +from .types.entity_type import DeleteEntityTypeRequest +from .types.entity_type import EntityType +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 ContinuousTestResult +from .types.environment import CreateEnvironmentRequest +from .types.environment import DeleteEnvironmentRequest +from .types.environment import Environment +from .types.environment import GetEnvironmentRequest +from .types.environment import ListContinuousTestResultsRequest +from .types.environment import ListContinuousTestResultsResponse +from .types.environment import ListEnvironmentsRequest +from .types.environment import ListEnvironmentsResponse +from .types.environment import LookupEnvironmentHistoryRequest +from .types.environment import LookupEnvironmentHistoryResponse +from .types.environment import RunContinuousTestMetadata +from .types.environment import RunContinuousTestRequest +from .types.environment import RunContinuousTestResponse +from .types.environment import UpdateEnvironmentRequest +from .types.experiment import CreateExperimentRequest +from .types.experiment import DeleteExperimentRequest +from .types.experiment import Experiment +from .types.experiment import GetExperimentRequest +from .types.experiment import ListExperimentsRequest +from .types.experiment import ListExperimentsResponse +from .types.experiment import StartExperimentRequest +from .types.experiment import StopExperimentRequest +from .types.experiment import UpdateExperimentRequest +from .types.experiment import VariantsHistory +from .types.experiment import VersionVariants +from .types.flow import CreateFlowRequest +from .types.flow import DeleteFlowRequest +from .types.flow import ExportFlowRequest +from .types.flow import ExportFlowResponse +from .types.flow import Flow +from .types.flow import FlowValidationResult +from .types.flow import GetFlowRequest +from .types.flow import GetFlowValidationResultRequest +from .types.flow import ImportFlowRequest +from .types.flow import ImportFlowResponse +from .types.flow import ListFlowsRequest +from .types.flow import ListFlowsResponse +from .types.flow import NluSettings +from .types.flow import TrainFlowRequest +from .types.flow import UpdateFlowRequest +from .types.flow import ValidateFlowRequest +from .types.fulfillment import Fulfillment +from .types.intent import CreateIntentRequest +from .types.intent import DeleteIntentRequest +from .types.intent import GetIntentRequest +from .types.intent import Intent +from .types.intent import ListIntentsRequest +from .types.intent import ListIntentsResponse +from .types.intent import UpdateIntentRequest +from .types.intent import IntentView +from .types.page import CreatePageRequest +from .types.page import DeletePageRequest +from .types.page import EventHandler +from .types.page import Form +from .types.page import GetPageRequest +from .types.page import ListPagesRequest +from .types.page import ListPagesResponse +from .types.page import Page +from .types.page import TransitionRoute +from .types.page import UpdatePageRequest +from .types.response_message import ResponseMessage +from .types.security_settings import CreateSecuritySettingsRequest +from .types.security_settings import DeleteSecuritySettingsRequest +from .types.security_settings import GetSecuritySettingsRequest +from .types.security_settings import ListSecuritySettingsRequest +from .types.security_settings import ListSecuritySettingsResponse +from .types.security_settings import SecuritySettings +from .types.security_settings import UpdateSecuritySettingsRequest +from .types.session import AudioInput +from .types.session import DetectIntentRequest +from .types.session import DetectIntentResponse +from .types.session import DtmfInput +from .types.session import EventInput +from .types.session import FulfillIntentRequest +from .types.session import FulfillIntentResponse +from .types.session import IntentInput +from .types.session import Match +from .types.session import MatchIntentRequest +from .types.session import MatchIntentResponse +from .types.session import QueryInput +from .types.session import QueryParameters +from .types.session import QueryResult +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.test_case import BatchDeleteTestCasesRequest +from .types.test_case import BatchRunTestCasesMetadata +from .types.test_case import BatchRunTestCasesRequest +from .types.test_case import BatchRunTestCasesResponse +from .types.test_case import CalculateCoverageRequest +from .types.test_case import CalculateCoverageResponse +from .types.test_case import ConversationTurn +from .types.test_case import CreateTestCaseRequest +from .types.test_case import ExportTestCasesMetadata +from .types.test_case import ExportTestCasesRequest +from .types.test_case import ExportTestCasesResponse +from .types.test_case import GetTestCaseRequest +from .types.test_case import GetTestCaseResultRequest +from .types.test_case import ImportTestCasesMetadata +from .types.test_case import ImportTestCasesRequest +from .types.test_case import ImportTestCasesResponse +from .types.test_case import IntentCoverage +from .types.test_case import ListTestCaseResultsRequest +from .types.test_case import ListTestCaseResultsResponse +from .types.test_case import ListTestCasesRequest +from .types.test_case import ListTestCasesResponse +from .types.test_case import RunTestCaseMetadata +from .types.test_case import RunTestCaseRequest +from .types.test_case import RunTestCaseResponse +from .types.test_case import TestCase +from .types.test_case import TestCaseError +from .types.test_case import TestCaseResult +from .types.test_case import TestConfig +from .types.test_case import TestError +from .types.test_case import TestRunDifference +from .types.test_case import TransitionCoverage +from .types.test_case import TransitionRouteGroupCoverage +from .types.test_case import UpdateTestCaseRequest +from .types.test_case import TestResult +from .types.transition_route_group import CreateTransitionRouteGroupRequest +from .types.transition_route_group import DeleteTransitionRouteGroupRequest +from .types.transition_route_group import GetTransitionRouteGroupRequest +from .types.transition_route_group import ListTransitionRouteGroupsRequest +from .types.transition_route_group import ListTransitionRouteGroupsResponse +from .types.transition_route_group import TransitionRouteGroup +from .types.transition_route_group import UpdateTransitionRouteGroupRequest +from .types.validation_message import ResourceName +from .types.validation_message import ValidationMessage +from .types.version import CreateVersionOperationMetadata +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 LoadVersionRequest +from .types.version import UpdateVersionRequest +from .types.version import Version +from .types.webhook import CreateWebhookRequest +from .types.webhook import DeleteWebhookRequest +from .types.webhook import GetWebhookRequest +from .types.webhook import ListWebhooksRequest +from .types.webhook import ListWebhooksResponse +from .types.webhook import PageInfo +from .types.webhook import SessionInfo +from .types.webhook import UpdateWebhookRequest +from .types.webhook import Webhook +from .types.webhook import WebhookRequest +from .types.webhook import WebhookResponse + +__all__ = ( + 'AgentsAsyncClient', + 'EntityTypesAsyncClient', + 'EnvironmentsAsyncClient', + 'ExperimentsAsyncClient', + 'FlowsAsyncClient', + 'IntentsAsyncClient', + 'PagesAsyncClient', + 'SecuritySettingsServiceAsyncClient', + 'SessionEntityTypesAsyncClient', + 'SessionsAsyncClient', + 'TestCasesAsyncClient', + 'TransitionRouteGroupsAsyncClient', + 'VersionsAsyncClient', + 'WebhooksAsyncClient', +'Agent', +'AgentValidationResult', +'AgentsClient', +'AudioEncoding', +'AudioInput', +'BatchDeleteTestCasesRequest', +'BatchRunTestCasesMetadata', +'BatchRunTestCasesRequest', +'BatchRunTestCasesResponse', +'CalculateCoverageRequest', +'CalculateCoverageResponse', +'ContinuousTestResult', +'ConversationTurn', +'CreateAgentRequest', +'CreateEntityTypeRequest', +'CreateEnvironmentRequest', +'CreateExperimentRequest', +'CreateFlowRequest', +'CreateIntentRequest', +'CreatePageRequest', +'CreateSecuritySettingsRequest', +'CreateSessionEntityTypeRequest', +'CreateTestCaseRequest', +'CreateTransitionRouteGroupRequest', +'CreateVersionOperationMetadata', +'CreateVersionRequest', +'CreateWebhookRequest', +'DeleteAgentRequest', +'DeleteEntityTypeRequest', +'DeleteEnvironmentRequest', +'DeleteExperimentRequest', +'DeleteFlowRequest', +'DeleteIntentRequest', +'DeletePageRequest', +'DeleteSecuritySettingsRequest', +'DeleteSessionEntityTypeRequest', +'DeleteTransitionRouteGroupRequest', +'DeleteVersionRequest', +'DeleteWebhookRequest', +'DetectIntentRequest', +'DetectIntentResponse', +'DtmfInput', +'EntityType', +'EntityTypesClient', +'Environment', +'EnvironmentsClient', +'EventHandler', +'EventInput', +'Experiment', +'ExperimentsClient', +'ExportAgentRequest', +'ExportAgentResponse', +'ExportFlowRequest', +'ExportFlowResponse', +'ExportTestCasesMetadata', +'ExportTestCasesRequest', +'ExportTestCasesResponse', +'Flow', +'FlowValidationResult', +'FlowsClient', +'Form', +'FulfillIntentRequest', +'FulfillIntentResponse', +'Fulfillment', +'GetAgentRequest', +'GetAgentValidationResultRequest', +'GetEntityTypeRequest', +'GetEnvironmentRequest', +'GetExperimentRequest', +'GetFlowRequest', +'GetFlowValidationResultRequest', +'GetIntentRequest', +'GetPageRequest', +'GetSecuritySettingsRequest', +'GetSessionEntityTypeRequest', +'GetTestCaseRequest', +'GetTestCaseResultRequest', +'GetTransitionRouteGroupRequest', +'GetVersionRequest', +'GetWebhookRequest', +'ImportFlowRequest', +'ImportFlowResponse', +'ImportTestCasesMetadata', +'ImportTestCasesRequest', +'ImportTestCasesResponse', +'InputAudioConfig', +'Intent', +'IntentCoverage', +'IntentInput', +'IntentView', +'IntentsClient', +'ListAgentsRequest', +'ListAgentsResponse', +'ListContinuousTestResultsRequest', +'ListContinuousTestResultsResponse', +'ListEntityTypesRequest', +'ListEntityTypesResponse', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListExperimentsRequest', +'ListExperimentsResponse', +'ListFlowsRequest', +'ListFlowsResponse', +'ListIntentsRequest', +'ListIntentsResponse', +'ListPagesRequest', +'ListPagesResponse', +'ListSecuritySettingsRequest', +'ListSecuritySettingsResponse', +'ListSessionEntityTypesRequest', +'ListSessionEntityTypesResponse', +'ListTestCaseResultsRequest', +'ListTestCaseResultsResponse', +'ListTestCasesRequest', +'ListTestCasesResponse', +'ListTransitionRouteGroupsRequest', +'ListTransitionRouteGroupsResponse', +'ListVersionsRequest', +'ListVersionsResponse', +'ListWebhooksRequest', +'ListWebhooksResponse', +'LoadVersionRequest', +'LookupEnvironmentHistoryRequest', +'LookupEnvironmentHistoryResponse', +'Match', +'MatchIntentRequest', +'MatchIntentResponse', +'NluSettings', +'OutputAudioConfig', +'OutputAudioEncoding', +'Page', +'PageInfo', +'PagesClient', +'QueryInput', +'QueryParameters', +'QueryResult', +'ResourceName', +'ResponseMessage', +'RestoreAgentRequest', +'RunContinuousTestMetadata', +'RunContinuousTestRequest', +'RunContinuousTestResponse', +'RunTestCaseMetadata', +'RunTestCaseRequest', +'RunTestCaseResponse', +'SecuritySettings', +'SecuritySettingsServiceClient', +'SentimentAnalysisResult', +'SessionEntityType', +'SessionEntityTypesClient', +'SessionInfo', +'SessionsClient', +'SpeechModelVariant', +'SpeechToTextSettings', +'SpeechWordInfo', +'SsmlVoiceGender', +'StartExperimentRequest', +'StopExperimentRequest', +'StreamingDetectIntentRequest', +'StreamingDetectIntentResponse', +'StreamingRecognitionResult', +'SynthesizeSpeechConfig', +'TestCase', +'TestCaseError', +'TestCaseResult', +'TestCasesClient', +'TestConfig', +'TestError', +'TestResult', +'TestRunDifference', +'TextInput', +'TrainFlowRequest', +'TransitionCoverage', +'TransitionRoute', +'TransitionRouteGroup', +'TransitionRouteGroupCoverage', +'TransitionRouteGroupsClient', +'UpdateAgentRequest', +'UpdateEntityTypeRequest', +'UpdateEnvironmentRequest', +'UpdateExperimentRequest', +'UpdateFlowRequest', +'UpdateIntentRequest', +'UpdatePageRequest', +'UpdateSecuritySettingsRequest', +'UpdateSessionEntityTypeRequest', +'UpdateTestCaseRequest', +'UpdateTransitionRouteGroupRequest', +'UpdateVersionRequest', +'UpdateWebhookRequest', +'ValidateAgentRequest', +'ValidateFlowRequest', +'ValidationMessage', +'VariantsHistory', +'Version', +'VersionVariants', +'VersionsClient', +'VoiceSelectionParams', +'Webhook', +'WebhookRequest', +'WebhookResponse', +'WebhooksClient', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json new file mode 100644 index 00000000..661610d7 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json @@ -0,0 +1,1115 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflowcx_v3beta1", + "protoPackage": "google.cloud.dialogflow.cx.v3beta1", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "get_agent_validation_result" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "ValidateAgent": { + "methods": [ + "validate_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "get_agent_validation_result" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "ValidateAgent": { + "methods": [ + "validate_agent" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EntityTypesAsyncClient", + "rpcs": { + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + } + } + }, + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListContinuousTestResults": { + "methods": [ + "list_continuous_test_results" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "lookup_environment_history" + ] + }, + "RunContinuousTest": { + "methods": [ + "run_continuous_test" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListContinuousTestResults": { + "methods": [ + "list_continuous_test_results" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "lookup_environment_history" + ] + }, + "RunContinuousTest": { + "methods": [ + "run_continuous_test" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Experiments": { + "clients": { + "grpc": { + "libraryClient": "ExperimentsClient", + "rpcs": { + "CreateExperiment": { + "methods": [ + "create_experiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "delete_experiment" + ] + }, + "GetExperiment": { + "methods": [ + "get_experiment" + ] + }, + "ListExperiments": { + "methods": [ + "list_experiments" + ] + }, + "StartExperiment": { + "methods": [ + "start_experiment" + ] + }, + "StopExperiment": { + "methods": [ + "stop_experiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "update_experiment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ExperimentsAsyncClient", + "rpcs": { + "CreateExperiment": { + "methods": [ + "create_experiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "delete_experiment" + ] + }, + "GetExperiment": { + "methods": [ + "get_experiment" + ] + }, + "ListExperiments": { + "methods": [ + "list_experiments" + ] + }, + "StartExperiment": { + "methods": [ + "start_experiment" + ] + }, + "StopExperiment": { + "methods": [ + "stop_experiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "update_experiment" + ] + } + } + } + } + }, + "Flows": { + "clients": { + "grpc": { + "libraryClient": "FlowsClient", + "rpcs": { + "CreateFlow": { + "methods": [ + "create_flow" + ] + }, + "DeleteFlow": { + "methods": [ + "delete_flow" + ] + }, + "ExportFlow": { + "methods": [ + "export_flow" + ] + }, + "GetFlow": { + "methods": [ + "get_flow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "get_flow_validation_result" + ] + }, + "ImportFlow": { + "methods": [ + "import_flow" + ] + }, + "ListFlows": { + "methods": [ + "list_flows" + ] + }, + "TrainFlow": { + "methods": [ + "train_flow" + ] + }, + "UpdateFlow": { + "methods": [ + "update_flow" + ] + }, + "ValidateFlow": { + "methods": [ + "validate_flow" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FlowsAsyncClient", + "rpcs": { + "CreateFlow": { + "methods": [ + "create_flow" + ] + }, + "DeleteFlow": { + "methods": [ + "delete_flow" + ] + }, + "ExportFlow": { + "methods": [ + "export_flow" + ] + }, + "GetFlow": { + "methods": [ + "get_flow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "get_flow_validation_result" + ] + }, + "ImportFlow": { + "methods": [ + "import_flow" + ] + }, + "ListFlows": { + "methods": [ + "list_flows" + ] + }, + "TrainFlow": { + "methods": [ + "train_flow" + ] + }, + "UpdateFlow": { + "methods": [ + "update_flow" + ] + }, + "ValidateFlow": { + "methods": [ + "validate_flow" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IntentsAsyncClient", + "rpcs": { + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "Pages": { + "clients": { + "grpc": { + "libraryClient": "PagesClient", + "rpcs": { + "CreatePage": { + "methods": [ + "create_page" + ] + }, + "DeletePage": { + "methods": [ + "delete_page" + ] + }, + "GetPage": { + "methods": [ + "get_page" + ] + }, + "ListPages": { + "methods": [ + "list_pages" + ] + }, + "UpdatePage": { + "methods": [ + "update_page" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PagesAsyncClient", + "rpcs": { + "CreatePage": { + "methods": [ + "create_page" + ] + }, + "DeletePage": { + "methods": [ + "delete_page" + ] + }, + "GetPage": { + "methods": [ + "get_page" + ] + }, + "ListPages": { + "methods": [ + "list_pages" + ] + }, + "UpdatePage": { + "methods": [ + "update_page" + ] + } + } + } + } + }, + "SecuritySettingsService": { + "clients": { + "grpc": { + "libraryClient": "SecuritySettingsServiceClient", + "rpcs": { + "CreateSecuritySettings": { + "methods": [ + "create_security_settings" + ] + }, + "DeleteSecuritySettings": { + "methods": [ + "delete_security_settings" + ] + }, + "GetSecuritySettings": { + "methods": [ + "get_security_settings" + ] + }, + "ListSecuritySettings": { + "methods": [ + "list_security_settings" + ] + }, + "UpdateSecuritySettings": { + "methods": [ + "update_security_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecuritySettingsServiceAsyncClient", + "rpcs": { + "CreateSecuritySettings": { + "methods": [ + "create_security_settings" + ] + }, + "DeleteSecuritySettings": { + "methods": [ + "delete_security_settings" + ] + }, + "GetSecuritySettings": { + "methods": [ + "get_security_settings" + ] + }, + "ListSecuritySettings": { + "methods": [ + "list_security_settings" + ] + }, + "UpdateSecuritySettings": { + "methods": [ + "update_security_settings" + ] + } + } + } + } + }, + "SessionEntityTypes": { + "clients": { + "grpc": { + "libraryClient": "SessionEntityTypesClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionEntityTypesAsyncClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + } + } + }, + "Sessions": { + "clients": { + "grpc": { + "libraryClient": "SessionsClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "FulfillIntent": { + "methods": [ + "fulfill_intent" + ] + }, + "MatchIntent": { + "methods": [ + "match_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "FulfillIntent": { + "methods": [ + "fulfill_intent" + ] + }, + "MatchIntent": { + "methods": [ + "match_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "TestCases": { + "clients": { + "grpc": { + "libraryClient": "TestCasesClient", + "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "batch_delete_test_cases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "batch_run_test_cases" + ] + }, + "CalculateCoverage": { + "methods": [ + "calculate_coverage" + ] + }, + "CreateTestCase": { + "methods": [ + "create_test_case" + ] + }, + "ExportTestCases": { + "methods": [ + "export_test_cases" + ] + }, + "GetTestCase": { + "methods": [ + "get_test_case" + ] + }, + "GetTestCaseResult": { + "methods": [ + "get_test_case_result" + ] + }, + "ImportTestCases": { + "methods": [ + "import_test_cases" + ] + }, + "ListTestCaseResults": { + "methods": [ + "list_test_case_results" + ] + }, + "ListTestCases": { + "methods": [ + "list_test_cases" + ] + }, + "RunTestCase": { + "methods": [ + "run_test_case" + ] + }, + "UpdateTestCase": { + "methods": [ + "update_test_case" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TestCasesAsyncClient", + "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "batch_delete_test_cases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "batch_run_test_cases" + ] + }, + "CalculateCoverage": { + "methods": [ + "calculate_coverage" + ] + }, + "CreateTestCase": { + "methods": [ + "create_test_case" + ] + }, + "ExportTestCases": { + "methods": [ + "export_test_cases" + ] + }, + "GetTestCase": { + "methods": [ + "get_test_case" + ] + }, + "GetTestCaseResult": { + "methods": [ + "get_test_case_result" + ] + }, + "ImportTestCases": { + "methods": [ + "import_test_cases" + ] + }, + "ListTestCaseResults": { + "methods": [ + "list_test_case_results" + ] + }, + "ListTestCases": { + "methods": [ + "list_test_cases" + ] + }, + "RunTestCase": { + "methods": [ + "run_test_case" + ] + }, + "UpdateTestCase": { + "methods": [ + "update_test_case" + ] + } + } + } + } + }, + "TransitionRouteGroups": { + "clients": { + "grpc": { + "libraryClient": "TransitionRouteGroupsClient", + "rpcs": { + "CreateTransitionRouteGroup": { + "methods": [ + "create_transition_route_group" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "delete_transition_route_group" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "get_transition_route_group" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "list_transition_route_groups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "update_transition_route_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TransitionRouteGroupsAsyncClient", + "rpcs": { + "CreateTransitionRouteGroup": { + "methods": [ + "create_transition_route_group" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "delete_transition_route_group" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "get_transition_route_group" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "list_transition_route_groups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "update_transition_route_group" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "LoadVersion": { + "methods": [ + "load_version" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "LoadVersion": { + "methods": [ + "load_version" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + }, + "Webhooks": { + "clients": { + "grpc": { + "libraryClient": "WebhooksClient", + "rpcs": { + "CreateWebhook": { + "methods": [ + "create_webhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "delete_webhook" + ] + }, + "GetWebhook": { + "methods": [ + "get_webhook" + ] + }, + "ListWebhooks": { + "methods": [ + "list_webhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "update_webhook" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebhooksAsyncClient", + "rpcs": { + "CreateWebhook": { + "methods": [ + "create_webhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "delete_webhook" + ] + }, + "GetWebhook": { + "methods": [ + "get_webhook" + ] + }, + "ListWebhooks": { + "methods": [ + "list_webhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "update_webhook" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/py.typed b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/py.typed new file mode 100644 index 00000000..60fdca49 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-dialogflowcx package uses inline types. diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py new file mode 100644 index 00000000..057c8b80 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py new file mode 100644 index 00000000..cf45251e --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py @@ -0,0 +1,894 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.agents import pagers +from google.cloud.dialogflowcx_v3beta1.types import agent +from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3beta1.types import flow +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport +from .client import AgentsClient + + +class AgentsAsyncClient: + """Service for managing + [Agents][google.cloud.dialogflow.cx.v3beta1.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) + agent_validation_result_path = staticmethod(AgentsClient.agent_validation_result_path) + parse_agent_validation_result_path = staticmethod(AgentsClient.parse_agent_validation_result_path) + environment_path = staticmethod(AgentsClient.environment_path) + parse_environment_path = staticmethod(AgentsClient.parse_environment_path) + flow_path = staticmethod(AgentsClient.flow_path) + parse_flow_path = staticmethod(AgentsClient.parse_flow_path) + flow_validation_result_path = staticmethod(AgentsClient.flow_validation_result_path) + parse_flow_validation_result_path = staticmethod(AgentsClient.parse_flow_validation_result_path) + security_settings_path = staticmethod(AgentsClient.security_settings_path) + parse_security_settings_path = staticmethod(AgentsClient.parse_security_settings_path) + common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AgentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AgentsClient.common_folder_path) + parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) + common_organization_path = staticmethod(AgentsClient.common_organization_path) + parse_common_organization_path = staticmethod(AgentsClient.parse_common_organization_path) + common_project_path = staticmethod(AgentsClient.common_project_path) + parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) + common_location_path = staticmethod(AgentsClient.common_location_path) + parse_common_location_path = staticmethod(AgentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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 list_agents(self, + request: agent.ListAgentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAgentsAsyncPager: + r"""Returns the list of all agents in the specified + location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsRequest`): + The request object. The request message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. + parent (:class:`str`): + Required. The location to list all agents 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.dialogflowcx_v3beta1.services.agents.pagers.ListAgentsAsyncPager: + The response message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. + + 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.ListAgentsRequest(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_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.ListAgentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_agent(self, + request: agent.GetAgentRequest = None, + *, + name: 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.dialogflowcx_v3beta1.types.GetAgentRequest`): + The request object. The request message for + [Agents.GetAgent][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgent]. + name (:class:`str`): + Required. The name of the agent. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3beta1.EntityType], + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = agent.GetAgentRequest(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_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(( + ("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_agent(self, + request: gcdc_agent.CreateAgentRequest = None, + *, + parent: str = None, + agent: gcdc_agent.Agent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Creates an agent in the specified location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateAgentRequest`): + The request object. The request message for + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.CreateAgent]. + parent (:class:`str`): + Required. The location to create a agent for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent (:class:`google.cloud.dialogflowcx_v3beta1.types.Agent`): + Required. The agent to create. + 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.dialogflowcx_v3beta1.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3beta1.EntityType], + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 = gcdc_agent.CreateAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if agent is not None: + 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.create_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 update_agent(self, + request: gcdc_agent.UpdateAgentRequest = None, + *, + agent: gcdc_agent.Agent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Updates the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateAgentRequest`): + The request object. The request message for + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent]. + agent (:class:`google.cloud.dialogflowcx_v3beta1.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. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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.dialogflowcx_v3beta1.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3beta1.EntityType], + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, 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 = gcdc_agent.UpdateAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + if update_mask is not None: + 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_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.name", request.agent.name), + )), + ) + + # 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, + *, + name: 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.dialogflowcx_v3beta1.types.DeleteAgentRequest`): + The request object. The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3beta1.Agents.DeleteAgent]. + name (:class:`str`): + Required. The name of the agent to delete. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = agent.DeleteAgentRequest(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_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(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def export_agent(self, + request: agent.ExportAgentRequest = 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 binary file. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportAgentRequest`): + The request object. The request message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ExportAgentResponse` + The response message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. + + """ + # Create or coerce a protobuf request object. + request = agent.ExportAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_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(( + ("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, + agent.ExportAgentResponse, + 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 binary file. + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, + flows) will be removed. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest`): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3beta1.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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(( + ("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=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def validate_agent(self, + request: agent.ValidateAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ValidateAgentRequest`): + The request object. The request message for + [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ValidateAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + request = agent.ValidateAgentRequest(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.validate_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(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_agent_validation_result(self, + request: agent.GetAgentValidationResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetAgentValidationResultRequest`): + The request object. The request message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. + name (:class:`str`): + Required. The agent name. Format: + ``projects//locations//agents//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = agent.GetAgentValidationResultRequest(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_agent_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(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AgentsAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/client.py new file mode 100644 index 00000000..1418254c --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/client.py @@ -0,0 +1,1129 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.agents import pagers +from google.cloud.dialogflowcx_v3beta1.types import agent +from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3beta1.types import flow +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AgentsGrpcTransport +from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport + + +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.cx.v3beta1.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,location: str,agent: str,) -> str: + """Returns a fully-qualified agent string.""" + return "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str,str]: + """Parses a agent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def agent_validation_result_path(project: str,location: str,agent: str,) -> str: + """Returns a fully-qualified agent_validation_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/validationResult".format(project=project, location=location, agent=agent, ) + + @staticmethod + def parse_agent_validation_result_path(path: str) -> Dict[str,str]: + """Parses a agent_validation_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/validationResult$", path) + return m.groupdict() if m else {} + + @staticmethod + def environment_path(project: str,location: str,agent: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_validation_result_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow_validation_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_validation_result_path(path: str) -> Dict[str,str]: + """Parses a flow_validation_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_settings_path(project: str,location: str,security_settings: str,) -> str: + """Returns a fully-qualified security_settings string.""" + return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + + @staticmethod + def parse_security_settings_path(path: str) -> Dict[str,str]: + """Parses a security_settings path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def 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 list_agents(self, + request: agent.ListAgentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAgentsPager: + r"""Returns the list of all agents in the specified + location. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListAgentsRequest): + The request object. The request message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. + parent (str): + Required. The location to list all agents 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.dialogflowcx_v3beta1.services.agents.pagers.ListAgentsPager: + The response message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. + + 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.ListAgentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ListAgentsRequest): + request = agent.ListAgentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_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.ListAgentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_agent(self, + request: agent.GetAgentRequest = None, + *, + name: 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.dialogflowcx_v3beta1.types.GetAgentRequest): + The request object. The request message for + [Agents.GetAgent][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgent]. + name (str): + Required. The name of the agent. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3beta1.EntityType], + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 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 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_agent] + + # Certain fields should be provided 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_agent(self, + request: gcdc_agent.CreateAgentRequest = None, + *, + parent: str = None, + agent: gcdc_agent.Agent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Creates an agent in the specified location. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateAgentRequest): + The request object. The request message for + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.CreateAgent]. + parent (str): + Required. The location to create a agent for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent (google.cloud.dialogflowcx_v3beta1.types.Agent): + Required. The agent to create. + 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.dialogflowcx_v3beta1.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3beta1.EntityType], + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, 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 gcdc_agent.CreateAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_agent.CreateAgentRequest): + request = gcdc_agent.CreateAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if agent is not None: + request.agent = agent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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 update_agent(self, + request: gcdc_agent.UpdateAgentRequest = None, + *, + agent: gcdc_agent.Agent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_agent.Agent: + r"""Updates the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateAgentRequest): + The request object. The request message for + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent]. + agent (google.cloud.dialogflowcx_v3beta1.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. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.dialogflowcx_v3beta1.types.Agent: + Agents are best described as Natural Language Understanding (NLU) modules + that transform user requests into actionable data. + You can include agents in your app, product, or + service to determine user intent and respond to the + user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], + [Entity + Types][google.cloud.dialogflow.cx.v3beta1.EntityType], + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], + and so on to manage the conversation flows.. + + """ + # Create or coerce a protobuf request object. + # Sanity 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, 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 gcdc_agent.UpdateAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_agent.UpdateAgentRequest): + request = gcdc_agent.UpdateAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + if update_mask is not None: + 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_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent.name", request.agent.name), + )), + ) + + # 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, + *, + name: 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.dialogflowcx_v3beta1.types.DeleteAgentRequest): + The request object. The request message for + [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3beta1.Agents.DeleteAgent]. + name (str): + Required. The name of the agent to delete. Format: + ``projects//locations//agents/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 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 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_agent] + + # Certain fields should be 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 export_agent(self, + request: agent.ExportAgentRequest = 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 binary file. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ExportAgentRequest): + The request object. The request message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ExportAgentResponse` + The response message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.ExportAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ExportAgentRequest): + request = agent.ExportAgentRequest(request) + + # 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(( + ("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, + agent.ExportAgentResponse, + 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 binary file. + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, + flows) will be removed. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest): + The request object. The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3beta1.Agents.RestoreAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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(( + ("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=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def validate_agent(self, + request: agent.ValidateAgentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ValidateAgentRequest): + The request object. The request message for + [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ValidateAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a agent.ValidateAgentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.ValidateAgentRequest): + request = agent.ValidateAgentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_agent_validation_result(self, + request: agent.GetAgentValidationResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> agent.AgentValidationResult: + r"""Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetAgentValidationResultRequest): + The request object. The request message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. + name (str): + Required. The agent name. Format: + ``projects//locations//agents//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.AgentValidationResult: + The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 agent.GetAgentValidationResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, agent.GetAgentValidationResultRequest): + request = agent.GetAgentValidationResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_agent_validation_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AgentsClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py new file mode 100644 index 00000000..2a032cb9 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.types import agent + + +class ListAgentsPager: + """A pager for iterating through ``list_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse` + 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.ListAgentsResponse], + request: agent.ListAgentsRequest, + response: agent.ListAgentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListAgentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse): + 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.ListAgentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[agent.ListAgentsResponse]: + 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 ListAgentsAsyncPager: + """A pager for iterating through ``list_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse` + 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.ListAgentsResponse]], + request: agent.ListAgentsRequest, + response: agent.ListAgentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListAgentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse): + 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.ListAgentsRequest(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.ListAgentsResponse]: + 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py new file mode 100644 index 00000000..0dc0c06c --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py new file mode 100644 index 00000000..bf1db172 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.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 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.dialogflowcx_v3beta1.types import agent +from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent +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-dialogflowcx', + ).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.list_agents: gapic_v1.method.wrap_method( + self.list_agents, + default_timeout=None, + client_info=client_info, + ), + self.get_agent: gapic_v1.method.wrap_method( + self.get_agent, + default_timeout=None, + client_info=client_info, + ), + self.create_agent: gapic_v1.method.wrap_method( + self.create_agent, + default_timeout=None, + client_info=client_info, + ), + self.update_agent: gapic_v1.method.wrap_method( + self.update_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.export_agent: gapic_v1.method.wrap_method( + self.export_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.validate_agent: gapic_v1.method.wrap_method( + self.validate_agent, + default_timeout=None, + client_info=client_info, + ), + self.get_agent_validation_result: gapic_v1.method.wrap_method( + self.get_agent_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 list_agents(self) -> Callable[ + [agent.ListAgentsRequest], + Union[ + agent.ListAgentsResponse, + Awaitable[agent.ListAgentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_agent(self) -> Callable[ + [agent.GetAgentRequest], + Union[ + agent.Agent, + Awaitable[agent.Agent] + ]]: + raise NotImplementedError() + + @property + def create_agent(self) -> Callable[ + [gcdc_agent.CreateAgentRequest], + Union[ + gcdc_agent.Agent, + Awaitable[gcdc_agent.Agent] + ]]: + raise NotImplementedError() + + @property + def update_agent(self) -> Callable[ + [gcdc_agent.UpdateAgentRequest], + Union[ + gcdc_agent.Agent, + Awaitable[gcdc_agent.Agent] + ]]: + raise NotImplementedError() + + @property + def delete_agent(self) -> Callable[ + [agent.DeleteAgentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def export_agent(self) -> Callable[ + [agent.ExportAgentRequest], + 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 validate_agent(self) -> Callable[ + [agent.ValidateAgentRequest], + Union[ + agent.AgentValidationResult, + Awaitable[agent.AgentValidationResult] + ]]: + raise NotImplementedError() + + @property + def get_agent_validation_result(self) -> Callable[ + [agent.GetAgentValidationResultRequest], + Union[ + agent.AgentValidationResult, + Awaitable[agent.AgentValidationResult] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'AgentsTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py new file mode 100644 index 00000000..4c79b5c3 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py @@ -0,0 +1,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import agent +from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent +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.cx.v3beta1.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 list_agents(self) -> Callable[ + [agent.ListAgentsRequest], + agent.ListAgentsResponse]: + r"""Return a callable for the list agents method over gRPC. + + Returns the list of all agents in the specified + location. + + Returns: + Callable[[~.ListAgentsRequest], + ~.ListAgentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_agents' not in self._stubs: + self._stubs['list_agents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Agents/ListAgents', + request_serializer=agent.ListAgentsRequest.serialize, + response_deserializer=agent.ListAgentsResponse.deserialize, + ) + return self._stubs['list_agents'] + + @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.cx.v3beta1.Agents/GetAgent', + request_serializer=agent.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs['get_agent'] + + @property + def create_agent(self) -> Callable[ + [gcdc_agent.CreateAgentRequest], + gcdc_agent.Agent]: + r"""Return a callable for the create agent method over gRPC. + + Creates an agent in the specified location. + + Returns: + Callable[[~.CreateAgentRequest], + ~.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 'create_agent' not in self._stubs: + self._stubs['create_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Agents/CreateAgent', + request_serializer=gcdc_agent.CreateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['create_agent'] + + @property + def update_agent(self) -> Callable[ + [gcdc_agent.UpdateAgentRequest], + gcdc_agent.Agent]: + r"""Return a callable for the update agent method over gRPC. + + Updates the specified agent. + + Returns: + Callable[[~.UpdateAgentRequest], + ~.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 'update_agent' not in self._stubs: + self._stubs['update_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Agents/UpdateAgent', + request_serializer=gcdc_agent.UpdateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['update_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.cx.v3beta1.Agents/DeleteAgent', + request_serializer=agent.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_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 binary file. + + 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.cx.v3beta1.Agents/ExportAgent', + request_serializer=agent.ExportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_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 binary file. + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, + flows) will be removed. + + 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.cx.v3beta1.Agents/RestoreAgent', + request_serializer=agent.RestoreAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_agent'] + + @property + def validate_agent(self) -> Callable[ + [agent.ValidateAgentRequest], + agent.AgentValidationResult]: + r"""Return a callable for the validate agent method over gRPC. + + Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Returns: + Callable[[~.ValidateAgentRequest], + ~.AgentValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_agent' not in self._stubs: + self._stubs['validate_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Agents/ValidateAgent', + request_serializer=agent.ValidateAgentRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['validate_agent'] + + @property + def get_agent_validation_result(self) -> Callable[ + [agent.GetAgentValidationResultRequest], + agent.AgentValidationResult]: + r"""Return a callable for the get agent validation result method over gRPC. + + Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Returns: + Callable[[~.GetAgentValidationResultRequest], + ~.AgentValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_validation_result' not in self._stubs: + self._stubs['get_agent_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Agents/GetAgentValidationResult', + request_serializer=agent.GetAgentValidationResultRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['get_agent_validation_result'] + + +__all__ = ( + 'AgentsGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py new file mode 100644 index 00000000..594f44a3 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py @@ -0,0 +1,490 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import agent +from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent +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.cx.v3beta1.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 list_agents(self) -> Callable[ + [agent.ListAgentsRequest], + Awaitable[agent.ListAgentsResponse]]: + r"""Return a callable for the list agents method over gRPC. + + Returns the list of all agents in the specified + location. + + Returns: + Callable[[~.ListAgentsRequest], + Awaitable[~.ListAgentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_agents' not in self._stubs: + self._stubs['list_agents'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Agents/ListAgents', + request_serializer=agent.ListAgentsRequest.serialize, + response_deserializer=agent.ListAgentsResponse.deserialize, + ) + return self._stubs['list_agents'] + + @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.cx.v3beta1.Agents/GetAgent', + request_serializer=agent.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs['get_agent'] + + @property + def create_agent(self) -> Callable[ + [gcdc_agent.CreateAgentRequest], + Awaitable[gcdc_agent.Agent]]: + r"""Return a callable for the create agent method over gRPC. + + Creates an agent in the specified location. + + Returns: + Callable[[~.CreateAgentRequest], + 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 'create_agent' not in self._stubs: + self._stubs['create_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Agents/CreateAgent', + request_serializer=gcdc_agent.CreateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['create_agent'] + + @property + def update_agent(self) -> Callable[ + [gcdc_agent.UpdateAgentRequest], + Awaitable[gcdc_agent.Agent]]: + r"""Return a callable for the update agent method over gRPC. + + Updates the specified agent. + + Returns: + Callable[[~.UpdateAgentRequest], + 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 'update_agent' not in self._stubs: + self._stubs['update_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Agents/UpdateAgent', + request_serializer=gcdc_agent.UpdateAgentRequest.serialize, + response_deserializer=gcdc_agent.Agent.deserialize, + ) + return self._stubs['update_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.cx.v3beta1.Agents/DeleteAgent', + request_serializer=agent.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_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 binary file. + + 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.cx.v3beta1.Agents/ExportAgent', + request_serializer=agent.ExportAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_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 binary file. + Replaces the current agent with a new one. Note that all + existing resources in agent (e.g. intents, entity types, + flows) will be removed. + + 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.cx.v3beta1.Agents/RestoreAgent', + request_serializer=agent.RestoreAgentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restore_agent'] + + @property + def validate_agent(self) -> Callable[ + [agent.ValidateAgentRequest], + Awaitable[agent.AgentValidationResult]]: + r"""Return a callable for the validate agent method over gRPC. + + Validates the specified agent and creates or updates + validation results. The agent in draft version is + validated. Please call this API after the training is + completed to get the complete validation results. + + Returns: + Callable[[~.ValidateAgentRequest], + Awaitable[~.AgentValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_agent' not in self._stubs: + self._stubs['validate_agent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Agents/ValidateAgent', + request_serializer=agent.ValidateAgentRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['validate_agent'] + + @property + def get_agent_validation_result(self) -> Callable[ + [agent.GetAgentValidationResultRequest], + Awaitable[agent.AgentValidationResult]]: + r"""Return a callable for the get agent validation result method over gRPC. + + Gets the latest agent validation result. Agent + validation is performed when ValidateAgent is called. + + Returns: + Callable[[~.GetAgentValidationResultRequest], + Awaitable[~.AgentValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_validation_result' not in self._stubs: + self._stubs['get_agent_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Agents/GetAgentValidationResult', + request_serializer=agent.GetAgentValidationResultRequest.serialize, + response_deserializer=agent.AgentValidationResult.deserialize, + ) + return self._stubs['get_agent_validation_result'] + + +__all__ = ( + 'AgentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py new file mode 100644 index 00000000..82dfe86f --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py new file mode 100644 index 00000000..66393794 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py @@ -0,0 +1,659 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.entity_types import pagers +from google.cloud.dialogflowcx_v3beta1.types import entity_type +from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type +from google.protobuf import field_mask_pb2 # 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.cx.v3beta1.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, + 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.dialogflowcx_v3beta1.types.ListEntityTypesRequest`): + The request object. The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.EntityTypes.ListEntityTypes]. + parent (:class:`str`): + Required. The agent to list all entity types for. + Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.entity_types.pagers.ListEntityTypesAsyncPager: + The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.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]) + if request is not 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 + + # 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, + 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.dialogflowcx_v3beta1.types.GetEntityTypeRequest`): + The request object. The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.GetEntityType]. + name (:class:`str`): + Required. The name of the entity type. Format: + ``projects//locations//agents//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. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not 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 + + # 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: gcdc_entity_type.CreateEntityTypeRequest = None, + *, + parent: str = None, + entity_type: gcdc_entity_type.EntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateEntityTypeRequest`): + The request object. The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.CreateEntityType]. + parent (:class:`str`): + Required. The agent to create a entity type for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type (:class:`google.cloud.dialogflowcx_v3beta1.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. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_entity_type.CreateEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type is not None: + request.entity_type = 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_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: gcdc_entity_type.UpdateEntityTypeRequest = None, + *, + entity_type: gcdc_entity_type.EntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Updates the specified entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateEntityTypeRequest`): + The request object. The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.UpdateEntityType]. + entity_type (:class:`google.cloud.dialogflowcx_v3beta1.types.EntityType`): + 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. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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.dialogflowcx_v3beta1.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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, 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 = gcdc_entity_type.UpdateEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entity_type is not None: + request.entity_type = entity_type + if update_mask is not None: + 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.dialogflowcx_v3beta1.types.DeleteEntityTypeRequest`): + The request object. The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.DeleteEntityType]. + name (:class:`str`): + Required. The name of the entity type to delete. Format: + ``projects//locations//agents//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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EntityTypesAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py new file mode 100644 index 00000000..7b237697 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py @@ -0,0 +1,846 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.entity_types import pagers +from google.cloud.dialogflowcx_v3beta1.types import entity_type +from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type +from google.protobuf import field_mask_pb2 # 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.cx.v3beta1.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,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?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, 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, + 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.dialogflowcx_v3beta1.types.ListEntityTypesRequest): + The request object. The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.EntityTypes.ListEntityTypes]. + parent (str): + Required. The agent to list all entity types for. + Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.entity_types.pagers.ListEntityTypesPager: + The response message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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 + + # 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, + 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.dialogflowcx_v3beta1.types.GetEntityTypeRequest): + The request object. The request message for + [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.GetEntityType]. + name (str): + Required. The name of the entity type. Format: + ``projects//locations//agents//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. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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 + + # 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: gcdc_entity_type.CreateEntityTypeRequest = None, + *, + parent: str = None, + entity_type: gcdc_entity_type.EntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Creates an entity type in the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateEntityTypeRequest): + The request object. The request message for + [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.CreateEntityType]. + parent (str): + Required. The agent to create a entity type for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + entity_type (google.cloud.dialogflowcx_v3beta1.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. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_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, gcdc_entity_type.CreateEntityTypeRequest): + request = gcdc_entity_type.CreateEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if entity_type is not None: + request.entity_type = entity_type + + # 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: gcdc_entity_type.UpdateEntityTypeRequest = None, + *, + entity_type: gcdc_entity_type.EntityType = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_entity_type.EntityType: + r"""Updates the specified entity type. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateEntityTypeRequest): + The request object. The request message for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.UpdateEntityType]. + entity_type (google.cloud.dialogflowcx_v3beta1.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. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.dialogflowcx_v3beta1.types.EntityType: + Entities are extracted from user input and represent parameters that are + meaningful to your application. For example, a date + range, a proper name such as a geographic location or + landmark, and so on. Entities represent actionable + data for your application. + + When you define an entity, you can also include + synonyms that all map to that entity. For example, + "soft drink", "soda", "pop", and so on. + + There are three types of entities: + + - **System** - entities that are defined by the + Dialogflow API for common data types such as date, + time, currency, and so on. A system entity is + represented by the EntityType type. + - **Custom** - entities that are defined by you that + represent actionable data that is meaningful to + your application. For example, you could define a + pizza.sauce entity for red or white pizza sauce, a + pizza.cheese entity for the different types of + cheese on a pizza, a pizza.topping entity for + different toppings, and so on. A custom entity is + represented by the EntityType type. + - **User** - entities that are built for an + individual user such as favorites, preferences, + playlists, and so on. A user entity is represented + by the + [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] + type. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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, 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 gcdc_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, gcdc_entity_type.UpdateEntityTypeRequest): + request = gcdc_entity_type.UpdateEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if entity_type is not None: + request.entity_type = entity_type + if update_mask is not None: + 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.dialogflowcx_v3beta1.types.DeleteEntityTypeRequest): + The request object. The request message for + [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.DeleteEntityType]. + name (str): + Required. The name of the entity type to delete. Format: + ``projects//locations//agents//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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EntityTypesClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py new file mode 100644 index 00000000..77181a32 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.types import entity_type + + +class ListEntityTypesPager: + """A pager for iterating through ``list_entity_types`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py new file mode 100644 index 00000000..1a2aa82d --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py new file mode 100644 index 00000000..5402dcfe --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/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.dialogflowcx_v3beta1.types import entity_type +from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +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, + ), + } + + @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[ + [gcdc_entity_type.CreateEntityTypeRequest], + Union[ + gcdc_entity_type.EntityType, + Awaitable[gcdc_entity_type.EntityType] + ]]: + raise NotImplementedError() + + @property + def update_entity_type(self) -> Callable[ + [gcdc_entity_type.UpdateEntityTypeRequest], + Union[ + gcdc_entity_type.EntityType, + Awaitable[gcdc_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() + + +__all__ = ( + 'EntityTypesTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py new file mode 100644 index 00000000..f56c3376 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/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.dialogflowcx_v3beta1.types import entity_type +from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO + + +class EntityTypesGrpcTransport(EntityTypesTransport): + """gRPC backend transport for EntityTypes. + + Service for managing + [EntityTypes][google.cloud.dialogflow.cx.v3beta1.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] = {} + + 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_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.cx.v3beta1.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.cx.v3beta1.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[ + [gcdc_entity_type.CreateEntityTypeRequest], + gcdc_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.cx.v3beta1.EntityTypes/CreateEntityType', + request_serializer=gcdc_entity_type.CreateEntityTypeRequest.serialize, + response_deserializer=gcdc_entity_type.EntityType.deserialize, + ) + return self._stubs['create_entity_type'] + + @property + def update_entity_type(self) -> Callable[ + [gcdc_entity_type.UpdateEntityTypeRequest], + gcdc_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.cx.v3beta1.EntityTypes/UpdateEntityType', + request_serializer=gcdc_entity_type.UpdateEntityTypeRequest.serialize, + response_deserializer=gcdc_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.cx.v3beta1.EntityTypes/DeleteEntityType', + request_serializer=entity_type.DeleteEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entity_type'] + + +__all__ = ( + 'EntityTypesGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py new file mode 100644 index 00000000..6352fc58 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/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.dialogflowcx_v3beta1.types import entity_type +from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type +from google.protobuf import empty_pb2 # 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.cx.v3beta1.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] = {} + + 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_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.cx.v3beta1.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.cx.v3beta1.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[ + [gcdc_entity_type.CreateEntityTypeRequest], + Awaitable[gcdc_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.cx.v3beta1.EntityTypes/CreateEntityType', + request_serializer=gcdc_entity_type.CreateEntityTypeRequest.serialize, + response_deserializer=gcdc_entity_type.EntityType.deserialize, + ) + return self._stubs['create_entity_type'] + + @property + def update_entity_type(self) -> Callable[ + [gcdc_entity_type.UpdateEntityTypeRequest], + Awaitable[gcdc_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.cx.v3beta1.EntityTypes/UpdateEntityType', + request_serializer=gcdc_entity_type.UpdateEntityTypeRequest.serialize, + response_deserializer=gcdc_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.cx.v3beta1.EntityTypes/DeleteEntityType', + request_serializer=entity_type.DeleteEntityTypeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_entity_type'] + + +__all__ = ( + 'EntityTypesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py new file mode 100644 index 00000000..a3ad29ec --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py new file mode 100644 index 00000000..3726bf8b --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py @@ -0,0 +1,883 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.environments import pagers +from google.cloud.dialogflowcx_v3beta1.types import environment +from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .client import EnvironmentsClient + + +class EnvironmentsAsyncClient: + """Service for managing + [Environments][google.cloud.dialogflow.cx.v3beta1.Environment]. + """ + + _client: EnvironmentsClient + + DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + + continuous_test_result_path = staticmethod(EnvironmentsClient.continuous_test_result_path) + parse_continuous_test_result_path = staticmethod(EnvironmentsClient.parse_continuous_test_result_path) + environment_path = staticmethod(EnvironmentsClient.environment_path) + parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) + test_case_result_path = staticmethod(EnvironmentsClient.test_case_result_path) + parse_test_case_result_path = staticmethod(EnvironmentsClient.parse_test_case_result_path) + version_path = staticmethod(EnvironmentsClient.version_path) + parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) + common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) + common_project_path = staticmethod(EnvironmentsClient.common_project_path) + parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) + common_location_path = staticmethod(EnvironmentsClient.common_location_path) + parse_common_location_path = staticmethod(EnvironmentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @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 environments in the specified + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListEnvironmentsRequest`): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.Environments.ListEnvironments]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to + list all environments for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.environments.pagers.ListEnvironmentsAsyncPager: + The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.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, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetEnvironmentRequest`): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.GetEnvironment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Environment: + Represents an environment for an + agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = environment.GetEnvironmentRequest(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_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: gcdc_environment.CreateEnvironmentRequest = None, + *, + parent: str = None, + environment: gcdc_environment.Environment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in + the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateEnvironmentRequest`): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.CreateEnvironment]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to + create an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (:class:`google.cloud.dialogflowcx_v3beta1.types.Environment`): + Required. The environment to create. + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3beta1.types.Environment` Represents an environment for an agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, environment]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_environment.CreateEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if environment is not None: + request.environment = environment + + # 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def update_environment(self, + request: gcdc_environment.UpdateEnvironmentRequest = None, + *, + environment: gcdc_environment.Environment = 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 + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateEnvironmentRequest`): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.UpdateEnvironment]. + environment (:class:`google.cloud.dialogflowcx_v3beta1.types.Environment`): + Required. The environment to update. + This corresponds to the ``environment`` 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3beta1.types.Environment` Represents an environment for an agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([environment, 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 = gcdc_environment.UpdateEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if environment is not None: + request.environment = environment + if update_mask is not None: + 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_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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def delete_environment(self, + request: environment.DeleteEnvironmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteEnvironmentRequest`): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.DeleteEnvironment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to delete. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = environment.DeleteEnvironmentRequest(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_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 lookup_environment_history(self, + request: environment.LookupEnvironmentHistoryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.LookupEnvironmentHistoryAsyncPager: + r"""Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryRequest`): + The request object. The request message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. + name (:class:`str`): + Required. Resource name of the environment to look up + the history for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.environments.pagers.LookupEnvironmentHistoryAsyncPager: + The response message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. + + 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([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 = environment.LookupEnvironmentHistoryRequest(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.lookup_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(( + ("name", request.name), + )), + ) + + # 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.LookupEnvironmentHistoryAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_continuous_test(self, + request: environment.RunContinuousTestRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestRequest`): + The request object. The request message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestResponse` + The response message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + + """ + # Create or coerce a protobuf request object. + request = environment.RunContinuousTestRequest(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.run_continuous_test, + default_timeout=None, + client_info=DEFAULT_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", request.environment), + )), + ) + + # 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, + environment.RunContinuousTestResponse, + metadata_type=environment.RunContinuousTestMetadata, + ) + + # Done; return the response. + return response + + async def list_continuous_test_results(self, + request: environment.ListContinuousTestResultsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContinuousTestResultsAsyncPager: + r"""Fetches a list of continuous test results for a given + environment. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest`): + The request object. The request message for + [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3beta1.Environments.ListContinuousTestResults]. + parent (:class:`str`): + Required. The environment to list results for. Format: + ``projects//locations//agents// 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.environments.pagers.ListContinuousTestResultsAsyncPager: + The response message for + [Environments.ListTestCaseResults][]. + + 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.ListContinuousTestResultsRequest(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_continuous_test_results, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListContinuousTestResultsAsyncPager( + 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EnvironmentsAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/client.py new file mode 100644 index 00000000..4110792f --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/client.py @@ -0,0 +1,1098 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.environments import pagers +from google.cloud.dialogflowcx_v3beta1.types import environment +from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EnvironmentsGrpcTransport +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport + + +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.cx.v3beta1.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 continuous_test_result_path(project: str,location: str,agent: str,environment: str,continuous_test_result: str,) -> str: + """Returns a fully-qualified continuous_test_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/continuousTestResults/{continuous_test_result}".format(project=project, location=location, agent=agent, environment=environment, continuous_test_result=continuous_test_result, ) + + @staticmethod + def parse_continuous_test_result_path(path: str) -> Dict[str,str]: + """Parses a continuous_test_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/continuousTestResults/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def environment_path(project: str,location: str,agent: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def test_case_result_path(project: str,location: str,agent: str,test_case: str,result: str,) -> str: + """Returns a fully-qualified test_case_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) + + @staticmethod + def parse_test_case_result_path(path: str) -> Dict[str,str]: + """Parses a test_case_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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, 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 environments in the specified + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListEnvironmentsRequest): + The request object. The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.Environments.ListEnvironments]. + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to + list all environments for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.environments.pagers.ListEnvironmentsPager: + The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.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, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetEnvironmentRequest): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.GetEnvironment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Environment: + Represents an environment for an + agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 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) + # 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_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: gcdc_environment.CreateEnvironmentRequest = None, + *, + parent: str = None, + environment: gcdc_environment.Environment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in + the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateEnvironmentRequest): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.CreateEnvironment]. + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to + create an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (google.cloud.dialogflowcx_v3beta1.types.Environment): + Required. The environment to create. + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3beta1.types.Environment` Represents an environment for an agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, environment]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_environment.CreateEnvironmentRequest): + request = gcdc_environment.CreateEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if environment is not None: + request.environment = environment + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def update_environment(self, + request: gcdc_environment.UpdateEnvironmentRequest = None, + *, + environment: gcdc_environment.Environment = 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 + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateEnvironmentRequest): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.UpdateEnvironment]. + environment (google.cloud.dialogflowcx_v3beta1.types.Environment): + Required. The environment to update. + This corresponds to the ``environment`` 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.dialogflowcx_v3beta1.types.Environment` Represents an environment for an agent. 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. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([environment, 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 gcdc_environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_environment.UpdateEnvironmentRequest): + request = gcdc_environment.UpdateEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if environment is not None: + request.environment = environment + if update_mask is not None: + 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_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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcdc_environment.Environment, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def delete_environment(self, + request: environment.DeleteEnvironmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.DeleteEnvironmentRequest): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.DeleteEnvironment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to delete. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 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) + # 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_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 lookup_environment_history(self, + request: environment.LookupEnvironmentHistoryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.LookupEnvironmentHistoryPager: + r"""Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryRequest): + The request object. The request message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. + name (str): + Required. Resource name of the environment to look up + the history for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.environments.pagers.LookupEnvironmentHistoryPager: + The response message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. + + 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([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 environment.LookupEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.LookupEnvironmentHistoryRequest): + request = environment.LookupEnvironmentHistoryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.lookup_environment_history] + + # Certain fields should be provided 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.LookupEnvironmentHistoryPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_continuous_test(self, + request: environment.RunContinuousTestRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestRequest): + The request object. The request message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestResponse` + The response message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.RunContinuousTestRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.RunContinuousTestRequest): + request = environment.RunContinuousTestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_continuous_test] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environment.RunContinuousTestResponse, + metadata_type=environment.RunContinuousTestMetadata, + ) + + # Done; return the response. + return response + + def list_continuous_test_results(self, + request: environment.ListContinuousTestResultsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContinuousTestResultsPager: + r"""Fetches a list of continuous test results for a given + environment. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest): + The request object. The request message for + [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3beta1.Environments.ListContinuousTestResults]. + parent (str): + Required. The environment to list results for. Format: + ``projects//locations//agents// 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.environments.pagers.ListContinuousTestResultsPager: + The response message for + [Environments.ListTestCaseResults][]. + + 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.ListContinuousTestResultsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.ListContinuousTestResultsRequest): + request = environment.ListContinuousTestResultsRequest(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_continuous_test_results] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListContinuousTestResultsPager( + 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EnvironmentsClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py new file mode 100644 index 00000000..d7df3198 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.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. +# +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.dialogflowcx_v3beta1.types import environment + + +class ListEnvironmentsPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.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 LookupEnvironmentHistoryPager: + """A pager for iterating through ``lookup_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse` object, and + provides an ``__iter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``LookupEnvironmentHistory`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse` + 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.LookupEnvironmentHistoryResponse], + request: environment.LookupEnvironmentHistoryRequest, + response: environment.LookupEnvironmentHistoryResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse): + 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.LookupEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[environment.LookupEnvironmentHistoryResponse]: + 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 LookupEnvironmentHistoryAsyncPager: + """A pager for iterating through ``lookup_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``LookupEnvironmentHistory`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse` + 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.LookupEnvironmentHistoryResponse]], + request: environment.LookupEnvironmentHistoryRequest, + response: environment.LookupEnvironmentHistoryResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse): + 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.LookupEnvironmentHistoryRequest(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.LookupEnvironmentHistoryResponse]: + 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 ListContinuousTestResultsPager: + """A pager for iterating through ``list_continuous_test_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``continuous_test_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListContinuousTestResults`` requests and continue to iterate + through the ``continuous_test_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` + 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.ListContinuousTestResultsResponse], + request: environment.ListContinuousTestResultsRequest, + response: environment.ListContinuousTestResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse): + 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.ListContinuousTestResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[environment.ListContinuousTestResultsResponse]: + 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.ContinuousTestResult]: + for page in self.pages: + yield from page.continuous_test_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListContinuousTestResultsAsyncPager: + """A pager for iterating through ``list_continuous_test_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``continuous_test_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListContinuousTestResults`` requests and continue to iterate + through the ``continuous_test_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` + 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.ListContinuousTestResultsResponse]], + request: environment.ListContinuousTestResultsRequest, + response: environment.ListContinuousTestResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse): + 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.ListContinuousTestResultsRequest(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.ListContinuousTestResultsResponse]: + 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.ContinuousTestResult]: + async def async_generator(): + async for page in self.pages: + for response in page.continuous_test_results: + 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py new file mode 100644 index 00000000..fac90efe --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py new file mode 100644 index 00000000..902dd17d --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py @@ -0,0 +1,290 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import environment +from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment +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-dialogflowcx', + ).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.lookup_environment_history: gapic_v1.method.wrap_method( + self.lookup_environment_history, + default_timeout=None, + client_info=client_info, + ), + self.run_continuous_test: gapic_v1.method.wrap_method( + self.run_continuous_test, + default_timeout=None, + client_info=client_info, + ), + self.list_continuous_test_results: gapic_v1.method.wrap_method( + self.list_continuous_test_results, + 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_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[ + [gcdc_environment.CreateEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_environment(self) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_environment(self) -> Callable[ + [environment.DeleteEnvironmentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def lookup_environment_history(self) -> Callable[ + [environment.LookupEnvironmentHistoryRequest], + Union[ + environment.LookupEnvironmentHistoryResponse, + Awaitable[environment.LookupEnvironmentHistoryResponse] + ]]: + raise NotImplementedError() + + @property + def run_continuous_test(self) -> Callable[ + [environment.RunContinuousTestRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_continuous_test_results(self) -> Callable[ + [environment.ListContinuousTestResultsRequest], + Union[ + environment.ListContinuousTestResultsResponse, + Awaitable[environment.ListContinuousTestResultsResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'EnvironmentsTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py new file mode 100644 index 00000000..59d45c65 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py @@ -0,0 +1,461 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import environment +from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment +from google.longrunning import operations_pb2 # type: ignore +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.cx.v3beta1.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] = {} + 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_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + environment.ListEnvironmentsResponse]: + r"""Return a callable for the list environments method over gRPC. + + Returns the list of all environments in the specified + [Agent][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.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 + [Environment][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Environments/GetEnvironment', + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def create_environment(self) -> Callable[ + [gcdc_environment.CreateEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the create environment method over gRPC. + + Creates an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in + the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['create_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Environments/CreateEnvironment', + request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_environment'] + + @property + def update_environment(self) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Environments/UpdateEnvironment', + request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + 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 + [Environment][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def lookup_environment_history(self) -> Callable[ + [environment.LookupEnvironmentHistoryRequest], + environment.LookupEnvironmentHistoryResponse]: + r"""Return a callable for the lookup environment history method over gRPC. + + Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.LookupEnvironmentHistoryRequest], + ~.LookupEnvironmentHistoryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'lookup_environment_history' not in self._stubs: + self._stubs['lookup_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Environments/LookupEnvironmentHistory', + request_serializer=environment.LookupEnvironmentHistoryRequest.serialize, + response_deserializer=environment.LookupEnvironmentHistoryResponse.deserialize, + ) + return self._stubs['lookup_environment_history'] + + @property + def run_continuous_test(self) -> Callable[ + [environment.RunContinuousTestRequest], + operations_pb2.Operation]: + r"""Return a callable for the run continuous test method over gRPC. + + Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.RunContinuousTestRequest], + ~.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 'run_continuous_test' not in self._stubs: + self._stubs['run_continuous_test'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Environments/RunContinuousTest', + request_serializer=environment.RunContinuousTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_continuous_test'] + + @property + def list_continuous_test_results(self) -> Callable[ + [environment.ListContinuousTestResultsRequest], + environment.ListContinuousTestResultsResponse]: + r"""Return a callable for the list continuous test results method over gRPC. + + Fetches a list of continuous test results for a given + environment. + + Returns: + Callable[[~.ListContinuousTestResultsRequest], + ~.ListContinuousTestResultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_continuous_test_results' not in self._stubs: + self._stubs['list_continuous_test_results'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Environments/ListContinuousTestResults', + request_serializer=environment.ListContinuousTestResultsRequest.serialize, + response_deserializer=environment.ListContinuousTestResultsResponse.deserialize, + ) + return self._stubs['list_continuous_test_results'] + + +__all__ = ( + 'EnvironmentsGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py new file mode 100644 index 00000000..8bdca952 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py @@ -0,0 +1,465 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import environment +from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import EnvironmentsGrpcTransport + + +class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): + """gRPC AsyncIO backend transport for Environments. + + Service for managing + [Environments][google.cloud.dialogflow.cx.v3beta1.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] = {} + 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_environments(self) -> Callable[ + [environment.ListEnvironmentsRequest], + Awaitable[environment.ListEnvironmentsResponse]]: + r"""Return a callable for the list environments method over gRPC. + + Returns the list of all environments in the specified + [Agent][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.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 + [Environment][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Environments/GetEnvironment', + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def create_environment(self) -> Callable[ + [gcdc_environment.CreateEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create environment method over gRPC. + + Creates an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in + the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. + + Returns: + Callable[[~.CreateEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['create_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Environments/CreateEnvironment', + request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_environment'] + + @property + def update_environment(self) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['update_environment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Environments/UpdateEnvironment', + request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + 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 + [Environment][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Environments/DeleteEnvironment', + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_environment'] + + @property + def lookup_environment_history(self) -> Callable[ + [environment.LookupEnvironmentHistoryRequest], + Awaitable[environment.LookupEnvironmentHistoryResponse]]: + r"""Return a callable for the lookup environment history method over gRPC. + + Looks up the history of the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.LookupEnvironmentHistoryRequest], + Awaitable[~.LookupEnvironmentHistoryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'lookup_environment_history' not in self._stubs: + self._stubs['lookup_environment_history'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Environments/LookupEnvironmentHistory', + request_serializer=environment.LookupEnvironmentHistoryRequest.serialize, + response_deserializer=environment.LookupEnvironmentHistoryResponse.deserialize, + ) + return self._stubs['lookup_environment_history'] + + @property + def run_continuous_test(self) -> Callable[ + [environment.RunContinuousTestRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run continuous test method over gRPC. + + Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.RunContinuousTestRequest], + 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 'run_continuous_test' not in self._stubs: + self._stubs['run_continuous_test'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Environments/RunContinuousTest', + request_serializer=environment.RunContinuousTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_continuous_test'] + + @property + def list_continuous_test_results(self) -> Callable[ + [environment.ListContinuousTestResultsRequest], + Awaitable[environment.ListContinuousTestResultsResponse]]: + r"""Return a callable for the list continuous test results method over gRPC. + + Fetches a list of continuous test results for a given + environment. + + Returns: + Callable[[~.ListContinuousTestResultsRequest], + Awaitable[~.ListContinuousTestResultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_continuous_test_results' not in self._stubs: + self._stubs['list_continuous_test_results'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Environments/ListContinuousTestResults', + request_serializer=environment.ListContinuousTestResultsRequest.serialize, + response_deserializer=environment.ListContinuousTestResultsResponse.deserialize, + ) + return self._stubs['list_continuous_test_results'] + + +__all__ = ( + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py new file mode 100644 index 00000000..6d4dd817 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/__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 ExperimentsClient +from .async_client import ExperimentsAsyncClient + +__all__ = ( + 'ExperimentsClient', + 'ExperimentsAsyncClient', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py new file mode 100644 index 00000000..1c87294c --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py @@ -0,0 +1,740 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.experiments import pagers +from google.cloud.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport +from .client import ExperimentsClient + + +class ExperimentsAsyncClient: + """Service for managing + [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. + """ + + _client: ExperimentsClient + + DEFAULT_ENDPOINT = ExperimentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ExperimentsClient.DEFAULT_MTLS_ENDPOINT + + experiment_path = staticmethod(ExperimentsClient.experiment_path) + parse_experiment_path = staticmethod(ExperimentsClient.parse_experiment_path) + version_path = staticmethod(ExperimentsClient.version_path) + parse_version_path = staticmethod(ExperimentsClient.parse_version_path) + common_billing_account_path = staticmethod(ExperimentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ExperimentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ExperimentsClient.common_folder_path) + parse_common_folder_path = staticmethod(ExperimentsClient.parse_common_folder_path) + common_organization_path = staticmethod(ExperimentsClient.common_organization_path) + parse_common_organization_path = staticmethod(ExperimentsClient.parse_common_organization_path) + common_project_path = staticmethod(ExperimentsClient.common_project_path) + parse_common_project_path = staticmethod(ExperimentsClient.parse_common_project_path) + common_location_path = staticmethod(ExperimentsClient.common_location_path) + parse_common_location_path = staticmethod(ExperimentsClient.parse_common_location_path) + + @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: + ExperimentsAsyncClient: The constructed client. + """ + return ExperimentsClient.from_service_account_info.__func__(ExperimentsAsyncClient, 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: + ExperimentsAsyncClient: The constructed client. + """ + return ExperimentsClient.from_service_account_file.__func__(ExperimentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ExperimentsTransport: + """Returns the transport used by the client instance. + + Returns: + ExperimentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ExperimentsClient).get_transport_class, type(ExperimentsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, ExperimentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the experiments 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, ~.ExperimentsTransport]): 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 = ExperimentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_experiments(self, + request: experiment.ListExperimentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExperimentsAsyncPager: + r"""Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsRequest`): + The request object. The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + parent (:class:`str`): + Required. The + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to list all environments for. Format: + ``projects//locations//agents//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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.experiments.pagers.ListExperimentsAsyncPager: + The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + + 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 = experiment.ListExperimentsRequest(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_experiments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListExperimentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_experiment(self, + request: experiment.GetExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetExperimentRequest`): + The request object. The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.GetExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.GetExperimentRequest(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_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_experiment(self, + request: gcdc_experiment.CreateExperimentRequest = None, + *, + parent: str = None, + experiment: gcdc_experiment.Experiment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Creates an + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in + the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateExperimentRequest`): + The request object. The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.CreateExperiment]. + parent (:class:`str`): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to + create an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + experiment (:class:`google.cloud.dialogflowcx_v3beta1.types.Experiment`): + Required. The experiment to create. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, experiment]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_experiment.CreateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if experiment is not None: + request.experiment = experiment + + # 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_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_experiment(self, + request: gcdc_experiment.UpdateExperimentRequest = None, + *, + experiment: gcdc_experiment.Experiment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateExperimentRequest`): + The request object. The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.UpdateExperiment]. + experiment (:class:`google.cloud.dialogflowcx_v3beta1.types.Experiment`): + Required. The experiment to update. + This corresponds to the ``experiment`` 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.dialogflowcx_v3beta1.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([experiment, 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 = gcdc_experiment.UpdateExperimentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if experiment is not None: + request.experiment = experiment + if update_mask is not None: + 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_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("experiment.name", request.experiment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_experiment(self, + request: experiment.DeleteExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteExperimentRequest`): + The request object. The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.DeleteExperiment]. + name (:class:`str`): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = experiment.DeleteExperimentRequest(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_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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 start_experiment(self, + request: experiment.StartExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from PENDING to + RUNNING. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.StartExperimentRequest`): + The request object. The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StartExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to start. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.StartExperimentRequest(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.start_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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 stop_experiment(self, + request: experiment.StopExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from RUNNING to + DONE. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.StopExperimentRequest`): + The request object. The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StopExperiment]. + name (:class:`str`): + Required. Resource name of the experiment to stop. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = experiment.StopExperimentRequest(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.stop_experiment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ExperimentsAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py new file mode 100644 index 00000000..fde48084 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py @@ -0,0 +1,936 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.experiments import pagers +from google.cloud.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ExperimentsGrpcTransport +from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport + + +class ExperimentsClientMeta(type): + """Metaclass for the Experiments 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[ExperimentsTransport]] + _transport_registry["grpc"] = ExperimentsGrpcTransport + _transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[ExperimentsTransport]: + """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 ExperimentsClient(metaclass=ExperimentsClientMeta): + """Service for managing + [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. + """ + + @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: + ExperimentsClient: 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: + ExperimentsClient: 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) -> ExperimentsTransport: + """Returns the transport used by the client instance. + + Returns: + ExperimentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def experiment_path(project: str,location: str,agent: str,environment: str,experiment: str,) -> str: + """Returns a fully-qualified experiment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format(project=project, location=location, agent=agent, environment=environment, experiment=experiment, ) + + @staticmethod + def parse_experiment_path(path: str) -> Dict[str,str]: + """Parses a experiment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/experiments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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, ExperimentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the experiments 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, ExperimentsTransport]): 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, ExperimentsTransport): + # transport is a ExperimentsTransport 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_experiments(self, + request: experiment.ListExperimentsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListExperimentsPager: + r"""Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsRequest): + The request object. The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + parent (str): + Required. The + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to list all environments for. Format: + ``projects//locations//agents//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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.experiments.pagers.ListExperimentsPager: + The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + + 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 experiment.ListExperimentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.ListExperimentsRequest): + request = experiment.ListExperimentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_experiments] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListExperimentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_experiment(self, + request: experiment.GetExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetExperimentRequest): + The request object. The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.GetExperiment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.GetExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.GetExperimentRequest): + request = experiment.GetExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_experiment] + + # Certain fields should be provided 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_experiment(self, + request: gcdc_experiment.CreateExperimentRequest = None, + *, + parent: str = None, + experiment: gcdc_experiment.Experiment = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Creates an + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in + the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateExperimentRequest): + The request object. The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.CreateExperiment]. + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to + create an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + for. Format: + ``projects//locations//agents//environments/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + experiment (google.cloud.dialogflowcx_v3beta1.types.Experiment): + Required. The experiment to create. + This corresponds to the ``experiment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, experiment]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_experiment.CreateExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_experiment.CreateExperimentRequest): + request = gcdc_experiment.CreateExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if experiment is not None: + request.experiment = experiment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_experiment(self, + request: gcdc_experiment.UpdateExperimentRequest = None, + *, + experiment: gcdc_experiment.Experiment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_experiment.Experiment: + r"""Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateExperimentRequest): + The request object. The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.UpdateExperiment]. + experiment (google.cloud.dialogflowcx_v3beta1.types.Experiment): + Required. The experiment to update. + This corresponds to the ``experiment`` 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.dialogflowcx_v3beta1.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([experiment, 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 gcdc_experiment.UpdateExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_experiment.UpdateExperimentRequest): + request = gcdc_experiment.UpdateExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if experiment is not None: + request.experiment = experiment + if update_mask is not None: + 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_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("experiment.name", request.experiment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_experiment(self, + request: experiment.DeleteExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.DeleteExperimentRequest): + The request object. The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.DeleteExperiment]. + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 experiment.DeleteExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.DeleteExperimentRequest): + request = experiment.DeleteExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_experiment] + + # Certain fields should be 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 start_experiment(self, + request: experiment.StartExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from PENDING to + RUNNING. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.StartExperimentRequest): + The request object. The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StartExperiment]. + name (str): + Required. Resource name of the experiment to start. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.StartExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.StartExperimentRequest): + request = experiment.StartExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.start_experiment] + + # Certain fields should be provided 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 stop_experiment(self, + request: experiment.StopExperimentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> experiment.Experiment: + r"""Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from RUNNING to + DONE. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.StopExperimentRequest): + The request object. The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StopExperiment]. + name (str): + Required. Resource name of the experiment to stop. + Format: + ``projects//locations//agents//environments//experiments/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Experiment: + Represents an experiment in an + environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a experiment.StopExperimentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, experiment.StopExperimentRequest): + request = experiment.StopExperimentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stop_experiment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "ExperimentsClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py new file mode 100644 index 00000000..8d269bae --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/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.dialogflowcx_v3beta1.types import experiment + + +class ListExperimentsPager: + """A pager for iterating through ``list_experiments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``experiments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExperiments`` requests and continue to iterate + through the ``experiments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse` + 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[..., experiment.ListExperimentsResponse], + request: experiment.ListExperimentsRequest, + response: experiment.ListExperimentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse): + 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 = experiment.ListExperimentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[experiment.ListExperimentsResponse]: + 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[experiment.Experiment]: + for page in self.pages: + yield from page.experiments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListExperimentsAsyncPager: + """A pager for iterating through ``list_experiments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``experiments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExperiments`` requests and continue to iterate + through the ``experiments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse` + 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[experiment.ListExperimentsResponse]], + request: experiment.ListExperimentsRequest, + response: experiment.ListExperimentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse): + 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 = experiment.ListExperimentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[experiment.ListExperimentsResponse]: + 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[experiment.Experiment]: + async def async_generator(): + async for page in self.pages: + for response in page.experiments: + 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py new file mode 100644 index 00000000..80f4c26e --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/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 ExperimentsTransport +from .grpc import ExperimentsGrpcTransport +from .grpc_asyncio import ExperimentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ExperimentsTransport]] +_transport_registry['grpc'] = ExperimentsGrpcTransport +_transport_registry['grpc_asyncio'] = ExperimentsGrpcAsyncIOTransport + +__all__ = ( + 'ExperimentsTransport', + 'ExperimentsGrpcTransport', + 'ExperimentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py new file mode 100644 index 00000000..21e09b9d --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +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-dialogflowcx', + ).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 ExperimentsTransport(abc.ABC): + """Abstract transport class for Experiments.""" + + 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_experiments: gapic_v1.method.wrap_method( + self.list_experiments, + default_timeout=None, + client_info=client_info, + ), + self.get_experiment: gapic_v1.method.wrap_method( + self.get_experiment, + default_timeout=None, + client_info=client_info, + ), + self.create_experiment: gapic_v1.method.wrap_method( + self.create_experiment, + default_timeout=None, + client_info=client_info, + ), + self.update_experiment: gapic_v1.method.wrap_method( + self.update_experiment, + default_timeout=None, + client_info=client_info, + ), + self.delete_experiment: gapic_v1.method.wrap_method( + self.delete_experiment, + default_timeout=None, + client_info=client_info, + ), + self.start_experiment: gapic_v1.method.wrap_method( + self.start_experiment, + default_timeout=None, + client_info=client_info, + ), + self.stop_experiment: gapic_v1.method.wrap_method( + self.stop_experiment, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_experiments(self) -> Callable[ + [experiment.ListExperimentsRequest], + Union[ + experiment.ListExperimentsResponse, + Awaitable[experiment.ListExperimentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_experiment(self) -> Callable[ + [experiment.GetExperimentRequest], + Union[ + experiment.Experiment, + Awaitable[experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def create_experiment(self) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], + Union[ + gcdc_experiment.Experiment, + Awaitable[gcdc_experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def update_experiment(self) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], + Union[ + gcdc_experiment.Experiment, + Awaitable[gcdc_experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def delete_experiment(self) -> Callable[ + [experiment.DeleteExperimentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def start_experiment(self) -> Callable[ + [experiment.StartExperimentRequest], + Union[ + experiment.Experiment, + Awaitable[experiment.Experiment] + ]]: + raise NotImplementedError() + + @property + def stop_experiment(self) -> Callable[ + [experiment.StopExperimentRequest], + Union[ + experiment.Experiment, + Awaitable[experiment.Experiment] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'ExperimentsTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py new file mode 100644 index 00000000..0e4f5139 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.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. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 # type: ignore +from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO + + +class ExperimentsGrpcTransport(ExperimentsTransport): + """gRPC backend transport for Experiments. + + Service for managing + [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + 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_experiments(self) -> Callable[ + [experiment.ListExperimentsRequest], + experiment.ListExperimentsResponse]: + r"""Return a callable for the list experiments method over gRPC. + + Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.ListExperimentsRequest], + ~.ListExperimentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_experiments' not in self._stubs: + self._stubs['list_experiments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/ListExperiments', + request_serializer=experiment.ListExperimentsRequest.serialize, + response_deserializer=experiment.ListExperimentsResponse.deserialize, + ) + return self._stubs['list_experiments'] + + @property + def get_experiment(self) -> Callable[ + [experiment.GetExperimentRequest], + experiment.Experiment]: + r"""Return a callable for the get experiment method over gRPC. + + Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.GetExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_experiment' not in self._stubs: + self._stubs['get_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/GetExperiment', + request_serializer=experiment.GetExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['get_experiment'] + + @property + def create_experiment(self) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], + gcdc_experiment.Experiment]: + r"""Return a callable for the create experiment method over gRPC. + + Creates an + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in + the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.CreateExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_experiment' not in self._stubs: + self._stubs['create_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/CreateExperiment', + request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['create_experiment'] + + @property + def update_experiment(self) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], + gcdc_experiment.Experiment]: + r"""Return a callable for the update experiment method over gRPC. + + Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.UpdateExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_experiment' not in self._stubs: + self._stubs['update_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/UpdateExperiment', + request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['update_experiment'] + + @property + def delete_experiment(self) -> Callable[ + [experiment.DeleteExperimentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete experiment method over gRPC. + + Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.DeleteExperimentRequest], + ~.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_experiment' not in self._stubs: + self._stubs['delete_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/DeleteExperiment', + request_serializer=experiment.DeleteExperimentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_experiment'] + + @property + def start_experiment(self) -> Callable[ + [experiment.StartExperimentRequest], + experiment.Experiment]: + r"""Return a callable for the start experiment method over gRPC. + + Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from PENDING to + RUNNING. + + Returns: + Callable[[~.StartExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_experiment' not in self._stubs: + self._stubs['start_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/StartExperiment', + request_serializer=experiment.StartExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['start_experiment'] + + @property + def stop_experiment(self) -> Callable[ + [experiment.StopExperimentRequest], + experiment.Experiment]: + r"""Return a callable for the stop experiment method over gRPC. + + Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from RUNNING to + DONE. + + Returns: + Callable[[~.StopExperimentRequest], + ~.Experiment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_experiment' not in self._stubs: + self._stubs['stop_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/StopExperiment', + request_serializer=experiment.StopExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['stop_experiment'] + + +__all__ = ( + 'ExperimentsGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py new file mode 100644 index 00000000..ee9dfee7 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.protobuf import empty_pb2 # type: ignore +from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO +from .grpc import ExperimentsGrpcTransport + + +class ExperimentsGrpcAsyncIOTransport(ExperimentsTransport): + """gRPC AsyncIO backend transport for Experiments. + + Service for managing + [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + 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_experiments(self) -> Callable[ + [experiment.ListExperimentsRequest], + Awaitable[experiment.ListExperimentsResponse]]: + r"""Return a callable for the list experiments method over gRPC. + + Returns the list of all experiments in the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.ListExperimentsRequest], + Awaitable[~.ListExperimentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_experiments' not in self._stubs: + self._stubs['list_experiments'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/ListExperiments', + request_serializer=experiment.ListExperimentsRequest.serialize, + response_deserializer=experiment.ListExperimentsResponse.deserialize, + ) + return self._stubs['list_experiments'] + + @property + def get_experiment(self) -> Callable[ + [experiment.GetExperimentRequest], + Awaitable[experiment.Experiment]]: + r"""Return a callable for the get experiment method over gRPC. + + Retrieves the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.GetExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_experiment' not in self._stubs: + self._stubs['get_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/GetExperiment', + request_serializer=experiment.GetExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['get_experiment'] + + @property + def create_experiment(self) -> Callable[ + [gcdc_experiment.CreateExperimentRequest], + Awaitable[gcdc_experiment.Experiment]]: + r"""Return a callable for the create experiment method over gRPC. + + Creates an + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in + the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.CreateExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_experiment' not in self._stubs: + self._stubs['create_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/CreateExperiment', + request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['create_experiment'] + + @property + def update_experiment(self) -> Callable[ + [gcdc_experiment.UpdateExperimentRequest], + Awaitable[gcdc_experiment.Experiment]]: + r"""Return a callable for the update experiment method over gRPC. + + Updates the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.UpdateExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_experiment' not in self._stubs: + self._stubs['update_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/UpdateExperiment', + request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, + response_deserializer=gcdc_experiment.Experiment.deserialize, + ) + return self._stubs['update_experiment'] + + @property + def delete_experiment(self) -> Callable[ + [experiment.DeleteExperimentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete experiment method over gRPC. + + Deletes the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + + Returns: + Callable[[~.DeleteExperimentRequest], + 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_experiment' not in self._stubs: + self._stubs['delete_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/DeleteExperiment', + request_serializer=experiment.DeleteExperimentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_experiment'] + + @property + def start_experiment(self) -> Callable[ + [experiment.StartExperimentRequest], + Awaitable[experiment.Experiment]]: + r"""Return a callable for the start experiment method over gRPC. + + Starts the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from PENDING to + RUNNING. + + Returns: + Callable[[~.StartExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'start_experiment' not in self._stubs: + self._stubs['start_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/StartExperiment', + request_serializer=experiment.StartExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['start_experiment'] + + @property + def stop_experiment(self) -> Callable[ + [experiment.StopExperimentRequest], + Awaitable[experiment.Experiment]]: + r"""Return a callable for the stop experiment method over gRPC. + + Stops the specified + [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. + This rpc only changes the state of experiment from RUNNING to + DONE. + + Returns: + Callable[[~.StopExperimentRequest], + Awaitable[~.Experiment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_experiment' not in self._stubs: + self._stubs['stop_experiment'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Experiments/StopExperiment', + request_serializer=experiment.StopExperimentRequest.serialize, + response_deserializer=experiment.Experiment.deserialize, + ) + return self._stubs['stop_experiment'] + + +__all__ = ( + 'ExperimentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py new file mode 100644 index 00000000..42e3f705 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/__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 FlowsClient +from .async_client import FlowsAsyncClient + +__all__ = ( + 'FlowsClient', + 'FlowsAsyncClient', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py new file mode 100644 index 00000000..0c60a6f7 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py @@ -0,0 +1,1010 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.flows import pagers +from google.cloud.dialogflowcx_v3beta1.types import flow +from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import validation_message +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport +from .client import FlowsClient + + +class FlowsAsyncClient: + """Service for managing + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow]. + """ + + _client: FlowsClient + + DEFAULT_ENDPOINT = FlowsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FlowsClient.DEFAULT_MTLS_ENDPOINT + + flow_path = staticmethod(FlowsClient.flow_path) + parse_flow_path = staticmethod(FlowsClient.parse_flow_path) + flow_validation_result_path = staticmethod(FlowsClient.flow_validation_result_path) + parse_flow_validation_result_path = staticmethod(FlowsClient.parse_flow_validation_result_path) + intent_path = staticmethod(FlowsClient.intent_path) + parse_intent_path = staticmethod(FlowsClient.parse_intent_path) + page_path = staticmethod(FlowsClient.page_path) + parse_page_path = staticmethod(FlowsClient.parse_page_path) + transition_route_group_path = staticmethod(FlowsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(FlowsClient.parse_transition_route_group_path) + webhook_path = staticmethod(FlowsClient.webhook_path) + parse_webhook_path = staticmethod(FlowsClient.parse_webhook_path) + common_billing_account_path = staticmethod(FlowsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(FlowsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(FlowsClient.common_folder_path) + parse_common_folder_path = staticmethod(FlowsClient.parse_common_folder_path) + common_organization_path = staticmethod(FlowsClient.common_organization_path) + parse_common_organization_path = staticmethod(FlowsClient.parse_common_organization_path) + common_project_path = staticmethod(FlowsClient.common_project_path) + parse_common_project_path = staticmethod(FlowsClient.parse_common_project_path) + common_location_path = staticmethod(FlowsClient.common_location_path) + parse_common_location_path = staticmethod(FlowsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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: + FlowsAsyncClient: The constructed client. + """ + return FlowsClient.from_service_account_info.__func__(FlowsAsyncClient, 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: + FlowsAsyncClient: The constructed client. + """ + return FlowsClient.from_service_account_file.__func__(FlowsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FlowsTransport: + """Returns the transport used by the client instance. + + Returns: + FlowsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(FlowsClient).get_transport_class, type(FlowsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FlowsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the flows 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, ~.FlowsTransport]): 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 = FlowsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_flow(self, + request: gcdc_flow.CreateFlowRequest = None, + *, + parent: str = None, + flow: gcdc_flow.Flow = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Creates a flow in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateFlowRequest`): + The request object. The request message for + [Flows.CreateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.CreateFlow]. + parent (:class:`str`): + Required. The agent to create a flow for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + flow (:class:`google.cloud.dialogflowcx_v3beta1.types.Flow`): + Required. The flow to create. + This corresponds to the ``flow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, flow]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_flow.CreateFlowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if flow is not None: + request.flow = flow + + # 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_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_flow(self, + request: flow.DeleteFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteFlowRequest`): + The request object. The request message for + [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3beta1.Flows.DeleteFlow]. + name (:class:`str`): + Required. The name of the flow to delete. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = flow.DeleteFlowRequest(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_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_flows(self, + request: flow.ListFlowsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFlowsAsyncPager: + r"""Returns the list of all flows in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsRequest`): + The request object. The request message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. + parent (:class:`str`): + Required. The agent containing the flows. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.flows.pagers.ListFlowsAsyncPager: + The response message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. + + 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 = flow.ListFlowsRequest(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_flows, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListFlowsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_flow(self, + request: flow.GetFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.Flow: + r"""Retrieves the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetFlowRequest`): + The request object. The response message for + [Flows.GetFlow][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlow]. + name (:class:`str`): + Required. The name of the flow to get. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = flow.GetFlowRequest(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_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_flow(self, + request: gcdc_flow.UpdateFlowRequest = None, + *, + flow: gcdc_flow.Flow = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Updates the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateFlowRequest`): + The request object. The request message for + [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.UpdateFlow]. + flow (:class:`google.cloud.dialogflowcx_v3beta1.types.Flow`): + Required. The flow to update. + This corresponds to the ``flow`` 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 ``update_mask`` is not specified, an error will be + returned. + + 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.dialogflowcx_v3beta1.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([flow, 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 = gcdc_flow.UpdateFlowRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if flow is not None: + request.flow = flow + if update_mask is not None: + 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_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("flow.name", request.flow.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def train_flow(self, + request: flow.TrainFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Trains the specified flow. Note that only the flow in + 'draft' environment is trained. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.TrainFlowRequest`): + The request object. The request message for + [Flows.TrainFlow][google.cloud.dialogflow.cx.v3beta1.Flows.TrainFlow]. + name (:class:`str`): + Required. The flow to train. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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 = flow.TrainFlowRequest(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.train_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def validate_flow(self, + request: flow.ValidateFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ValidateFlowRequest`): + The request object. The request message for + [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ValidateFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + request = flow.ValidateFlowRequest(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.validate_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_flow_validation_result(self, + request: flow.GetFlowValidationResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetFlowValidationResultRequest`): + The request object. The request message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. + name (:class:`str`): + Required. The flow name. Format: + ``projects//locations//agents//flows//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = flow.GetFlowValidationResultRequest(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_flow_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(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_flow(self, + request: flow.ImportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the specified flow to the specified agent + from a binary file. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest`): + The request object. The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ImportFlowResponse` + The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + + """ + # Create or coerce a protobuf request object. + request = flow.ImportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + flow.ImportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def export_flow(self, + request: flow.ExportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowRequest`): + The request object. The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowResponse` + The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + + """ + # Create or coerce a protobuf request object. + request = flow.ExportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + flow.ExportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FlowsAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/client.py new file mode 100644 index 00000000..16366dcd --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/client.py @@ -0,0 +1,1245 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.flows import pagers +from google.cloud.dialogflowcx_v3beta1.types import flow +from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import validation_message +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FlowsGrpcTransport +from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport + + +class FlowsClientMeta(type): + """Metaclass for the Flows 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[FlowsTransport]] + _transport_registry["grpc"] = FlowsGrpcTransport + _transport_registry["grpc_asyncio"] = FlowsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[FlowsTransport]: + """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 FlowsClient(metaclass=FlowsClientMeta): + """Service for managing + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow]. + """ + + @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: + FlowsClient: 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: + FlowsClient: 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) -> FlowsTransport: + """Returns the transport used by the client instance. + + Returns: + FlowsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_validation_result_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow_validation_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_validation_result_path(path: str) -> Dict[str,str]: + """Parses a flow_validation_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, FlowsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the flows 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, FlowsTransport]): 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, FlowsTransport): + # transport is a FlowsTransport 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_flow(self, + request: gcdc_flow.CreateFlowRequest = None, + *, + parent: str = None, + flow: gcdc_flow.Flow = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Creates a flow in the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateFlowRequest): + The request object. The request message for + [Flows.CreateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.CreateFlow]. + parent (str): + Required. The agent to create a flow for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + flow (google.cloud.dialogflowcx_v3beta1.types.Flow): + Required. The flow to create. + This corresponds to the ``flow`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, flow]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_flow.CreateFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_flow.CreateFlowRequest): + request = gcdc_flow.CreateFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if flow is not None: + request.flow = flow + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_flow(self, + request: flow.DeleteFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a specified flow. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.DeleteFlowRequest): + The request object. The request message for + [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3beta1.Flows.DeleteFlow]. + name (str): + Required. The name of the flow to delete. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 flow.DeleteFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.DeleteFlowRequest): + request = flow.DeleteFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_flows(self, + request: flow.ListFlowsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFlowsPager: + r"""Returns the list of all flows in the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListFlowsRequest): + The request object. The request message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. + parent (str): + Required. The agent containing the flows. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.flows.pagers.ListFlowsPager: + The response message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. + + 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 flow.ListFlowsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ListFlowsRequest): + request = flow.ListFlowsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_flows] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListFlowsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_flow(self, + request: flow.GetFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.Flow: + r"""Retrieves the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetFlowRequest): + The request object. The response message for + [Flows.GetFlow][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlow]. + name (str): + Required. The name of the flow to get. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 flow.GetFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.GetFlowRequest): + request = flow.GetFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_flow(self, + request: gcdc_flow.UpdateFlowRequest = None, + *, + flow: gcdc_flow.Flow = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_flow.Flow: + r"""Updates the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateFlowRequest): + The request object. The request message for + [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.UpdateFlow]. + flow (google.cloud.dialogflowcx_v3beta1.types.Flow): + Required. The flow to update. + This corresponds to the ``flow`` 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 ``update_mask`` is not specified, an error will be + returned. + + 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.dialogflowcx_v3beta1.types.Flow: + Flows represents the conversation + flows when you build your chatbot agent. + A flow consists of many pages connected + by the transition routes. Conversations + always start with the built-in Start + Flow (with an all-0 ID). Transition + routes can direct the conversation + session from the current flow (parent + flow) to another flow (sub flow). When + the sub flow is finished, Dialogflow + will bring the session back to the + parent flow, where the sub flow is + started. + + Usually, when a transition route is + followed by a matched intent, the intent + will be "consumed". This means the + intent won't activate more transition + routes. However, when the followed + transition route moves the conversation + session into a different flow, the + matched intent can be carried over and + to be consumed in the target flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([flow, 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 gcdc_flow.UpdateFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_flow.UpdateFlowRequest): + request = gcdc_flow.UpdateFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if flow is not None: + request.flow = flow + if update_mask is not None: + 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_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("flow.name", request.flow.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def train_flow(self, + request: flow.TrainFlowRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Trains the specified flow. Note that only the flow in + 'draft' environment is trained. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.TrainFlowRequest): + The request object. The request message for + [Flows.TrainFlow][google.cloud.dialogflow.cx.v3beta1.Flows.TrainFlow]. + name (str): + Required. The flow to train. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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 flow.TrainFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.TrainFlowRequest): + request = flow.TrainFlowRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.train_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def validate_flow(self, + request: flow.ValidateFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ValidateFlowRequest): + The request object. The request message for + [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ValidateFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ValidateFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ValidateFlowRequest): + request = flow.ValidateFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_flow_validation_result(self, + request: flow.GetFlowValidationResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> flow.FlowValidationResult: + r"""Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetFlowValidationResultRequest): + The request object. The request message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. + name (str): + Required. The flow name. Format: + ``projects//locations//agents//flows//validationResult``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.FlowValidationResult: + The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 flow.GetFlowValidationResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.GetFlowValidationResultRequest): + request = flow.GetFlowValidationResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_flow_validation_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_flow(self, + request: flow.ImportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports the specified flow to the specified agent + from a binary file. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest): + The request object. The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ImportFlowResponse` + The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ImportFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ImportFlowRequest): + request = flow.ImportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + flow.ImportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def export_flow(self, + request: flow.ExportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ExportFlowRequest): + The request object. The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowResponse` + The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ExportFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ExportFlowRequest): + request = flow.ExportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_flow] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + flow.ExportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "FlowsClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py new file mode 100644 index 00000000..c1e7bc19 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/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.dialogflowcx_v3beta1.types import flow + + +class ListFlowsPager: + """A pager for iterating through ``list_flows`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``flows`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFlows`` requests and continue to iterate + through the ``flows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse` + 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[..., flow.ListFlowsResponse], + request: flow.ListFlowsRequest, + response: flow.ListFlowsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListFlowsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse): + 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 = flow.ListFlowsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[flow.ListFlowsResponse]: + 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[flow.Flow]: + for page in self.pages: + yield from page.flows + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFlowsAsyncPager: + """A pager for iterating through ``list_flows`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``flows`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFlows`` requests and continue to iterate + through the ``flows`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse` + 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[flow.ListFlowsResponse]], + request: flow.ListFlowsRequest, + response: flow.ListFlowsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListFlowsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse): + 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 = flow.ListFlowsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[flow.ListFlowsResponse]: + 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[flow.Flow]: + async def async_generator(): + async for page in self.pages: + for response in page.flows: + 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py new file mode 100644 index 00000000..4ba28aff --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/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 FlowsTransport +from .grpc import FlowsGrpcTransport +from .grpc_asyncio import FlowsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FlowsTransport]] +_transport_registry['grpc'] = FlowsGrpcTransport +_transport_registry['grpc_asyncio'] = FlowsGrpcAsyncIOTransport + +__all__ = ( + 'FlowsTransport', + 'FlowsGrpcTransport', + 'FlowsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py new file mode 100644 index 00000000..1afa01a6 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/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.dialogflowcx_v3beta1.types import flow +from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow +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-dialogflowcx', + ).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 FlowsTransport(abc.ABC): + """Abstract transport class for Flows.""" + + 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_flow: gapic_v1.method.wrap_method( + self.create_flow, + default_timeout=None, + client_info=client_info, + ), + self.delete_flow: gapic_v1.method.wrap_method( + self.delete_flow, + default_timeout=None, + client_info=client_info, + ), + self.list_flows: gapic_v1.method.wrap_method( + self.list_flows, + default_timeout=None, + client_info=client_info, + ), + self.get_flow: gapic_v1.method.wrap_method( + self.get_flow, + default_timeout=None, + client_info=client_info, + ), + self.update_flow: gapic_v1.method.wrap_method( + self.update_flow, + default_timeout=None, + client_info=client_info, + ), + self.train_flow: gapic_v1.method.wrap_method( + self.train_flow, + default_timeout=None, + client_info=client_info, + ), + self.validate_flow: gapic_v1.method.wrap_method( + self.validate_flow, + default_timeout=None, + client_info=client_info, + ), + self.get_flow_validation_result: gapic_v1.method.wrap_method( + self.get_flow_validation_result, + default_timeout=None, + client_info=client_info, + ), + self.import_flow: gapic_v1.method.wrap_method( + self.import_flow, + default_timeout=None, + client_info=client_info, + ), + self.export_flow: gapic_v1.method.wrap_method( + self.export_flow, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_flow(self) -> Callable[ + [gcdc_flow.CreateFlowRequest], + Union[ + gcdc_flow.Flow, + Awaitable[gcdc_flow.Flow] + ]]: + raise NotImplementedError() + + @property + def delete_flow(self) -> Callable[ + [flow.DeleteFlowRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_flows(self) -> Callable[ + [flow.ListFlowsRequest], + Union[ + flow.ListFlowsResponse, + Awaitable[flow.ListFlowsResponse] + ]]: + raise NotImplementedError() + + @property + def get_flow(self) -> Callable[ + [flow.GetFlowRequest], + Union[ + flow.Flow, + Awaitable[flow.Flow] + ]]: + raise NotImplementedError() + + @property + def update_flow(self) -> Callable[ + [gcdc_flow.UpdateFlowRequest], + Union[ + gcdc_flow.Flow, + Awaitable[gcdc_flow.Flow] + ]]: + raise NotImplementedError() + + @property + def train_flow(self) -> Callable[ + [flow.TrainFlowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def validate_flow(self) -> Callable[ + [flow.ValidateFlowRequest], + Union[ + flow.FlowValidationResult, + Awaitable[flow.FlowValidationResult] + ]]: + raise NotImplementedError() + + @property + def get_flow_validation_result(self) -> Callable[ + [flow.GetFlowValidationResultRequest], + Union[ + flow.FlowValidationResult, + Awaitable[flow.FlowValidationResult] + ]]: + raise NotImplementedError() + + @property + def import_flow(self) -> Callable[ + [flow.ImportFlowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_flow(self) -> Callable[ + [flow.ExportFlowRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'FlowsTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py new file mode 100644 index 00000000..2eae3bee --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import flow +from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import FlowsTransport, DEFAULT_CLIENT_INFO + + +class FlowsGrpcTransport(FlowsTransport): + """gRPC backend transport for Flows. + + Service for managing + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow]. + + 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 create_flow(self) -> Callable[ + [gcdc_flow.CreateFlowRequest], + gcdc_flow.Flow]: + r"""Return a callable for the create flow method over gRPC. + + Creates a flow in the specified agent. + + Returns: + Callable[[~.CreateFlowRequest], + ~.Flow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_flow' not in self._stubs: + self._stubs['create_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/CreateFlow', + request_serializer=gcdc_flow.CreateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['create_flow'] + + @property + def delete_flow(self) -> Callable[ + [flow.DeleteFlowRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete flow method over gRPC. + + Deletes a specified flow. + + Returns: + Callable[[~.DeleteFlowRequest], + ~.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_flow' not in self._stubs: + self._stubs['delete_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/DeleteFlow', + request_serializer=flow.DeleteFlowRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_flow'] + + @property + def list_flows(self) -> Callable[ + [flow.ListFlowsRequest], + flow.ListFlowsResponse]: + r"""Return a callable for the list flows method over gRPC. + + Returns the list of all flows in the specified agent. + + Returns: + Callable[[~.ListFlowsRequest], + ~.ListFlowsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_flows' not in self._stubs: + self._stubs['list_flows'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/ListFlows', + request_serializer=flow.ListFlowsRequest.serialize, + response_deserializer=flow.ListFlowsResponse.deserialize, + ) + return self._stubs['list_flows'] + + @property + def get_flow(self) -> Callable[ + [flow.GetFlowRequest], + flow.Flow]: + r"""Return a callable for the get flow method over gRPC. + + Retrieves the specified flow. + + Returns: + Callable[[~.GetFlowRequest], + ~.Flow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow' not in self._stubs: + self._stubs['get_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/GetFlow', + request_serializer=flow.GetFlowRequest.serialize, + response_deserializer=flow.Flow.deserialize, + ) + return self._stubs['get_flow'] + + @property + def update_flow(self) -> Callable[ + [gcdc_flow.UpdateFlowRequest], + gcdc_flow.Flow]: + r"""Return a callable for the update flow method over gRPC. + + Updates the specified flow. + + Returns: + Callable[[~.UpdateFlowRequest], + ~.Flow]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_flow' not in self._stubs: + self._stubs['update_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/UpdateFlow', + request_serializer=gcdc_flow.UpdateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['update_flow'] + + @property + def train_flow(self) -> Callable[ + [flow.TrainFlowRequest], + operations_pb2.Operation]: + r"""Return a callable for the train flow method over gRPC. + + Trains the specified flow. Note that only the flow in + 'draft' environment is trained. + + Returns: + Callable[[~.TrainFlowRequest], + ~.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_flow' not in self._stubs: + self._stubs['train_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/TrainFlow', + request_serializer=flow.TrainFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['train_flow'] + + @property + def validate_flow(self) -> Callable[ + [flow.ValidateFlowRequest], + flow.FlowValidationResult]: + r"""Return a callable for the validate flow method over gRPC. + + Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Returns: + Callable[[~.ValidateFlowRequest], + ~.FlowValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_flow' not in self._stubs: + self._stubs['validate_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/ValidateFlow', + request_serializer=flow.ValidateFlowRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['validate_flow'] + + @property + def get_flow_validation_result(self) -> Callable[ + [flow.GetFlowValidationResultRequest], + flow.FlowValidationResult]: + r"""Return a callable for the get flow validation result method over gRPC. + + Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Returns: + Callable[[~.GetFlowValidationResultRequest], + ~.FlowValidationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow_validation_result' not in self._stubs: + self._stubs['get_flow_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/GetFlowValidationResult', + request_serializer=flow.GetFlowValidationResultRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['get_flow_validation_result'] + + @property + def import_flow(self) -> Callable[ + [flow.ImportFlowRequest], + operations_pb2.Operation]: + r"""Return a callable for the import flow method over gRPC. + + Imports the specified flow to the specified agent + from a binary file. + + Returns: + Callable[[~.ImportFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_flow' not in self._stubs: + self._stubs['import_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/ImportFlow', + request_serializer=flow.ImportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_flow'] + + @property + def export_flow(self) -> Callable[ + [flow.ExportFlowRequest], + operations_pb2.Operation]: + r"""Return a callable for the export flow method over gRPC. + + Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Returns: + Callable[[~.ExportFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_flow' not in self._stubs: + self._stubs['export_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/ExportFlow', + request_serializer=flow.ExportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_flow'] + + +__all__ = ( + 'FlowsGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py new file mode 100644 index 00000000..b038bb29 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py @@ -0,0 +1,516 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import flow +from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import FlowsTransport, DEFAULT_CLIENT_INFO +from .grpc import FlowsGrpcTransport + + +class FlowsGrpcAsyncIOTransport(FlowsTransport): + """gRPC AsyncIO backend transport for Flows. + + Service for managing + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow]. + + 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 create_flow(self) -> Callable[ + [gcdc_flow.CreateFlowRequest], + Awaitable[gcdc_flow.Flow]]: + r"""Return a callable for the create flow method over gRPC. + + Creates a flow in the specified agent. + + Returns: + Callable[[~.CreateFlowRequest], + Awaitable[~.Flow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_flow' not in self._stubs: + self._stubs['create_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/CreateFlow', + request_serializer=gcdc_flow.CreateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['create_flow'] + + @property + def delete_flow(self) -> Callable[ + [flow.DeleteFlowRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete flow method over gRPC. + + Deletes a specified flow. + + Returns: + Callable[[~.DeleteFlowRequest], + 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_flow' not in self._stubs: + self._stubs['delete_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/DeleteFlow', + request_serializer=flow.DeleteFlowRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_flow'] + + @property + def list_flows(self) -> Callable[ + [flow.ListFlowsRequest], + Awaitable[flow.ListFlowsResponse]]: + r"""Return a callable for the list flows method over gRPC. + + Returns the list of all flows in the specified agent. + + Returns: + Callable[[~.ListFlowsRequest], + Awaitable[~.ListFlowsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_flows' not in self._stubs: + self._stubs['list_flows'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/ListFlows', + request_serializer=flow.ListFlowsRequest.serialize, + response_deserializer=flow.ListFlowsResponse.deserialize, + ) + return self._stubs['list_flows'] + + @property + def get_flow(self) -> Callable[ + [flow.GetFlowRequest], + Awaitable[flow.Flow]]: + r"""Return a callable for the get flow method over gRPC. + + Retrieves the specified flow. + + Returns: + Callable[[~.GetFlowRequest], + Awaitable[~.Flow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow' not in self._stubs: + self._stubs['get_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/GetFlow', + request_serializer=flow.GetFlowRequest.serialize, + response_deserializer=flow.Flow.deserialize, + ) + return self._stubs['get_flow'] + + @property + def update_flow(self) -> Callable[ + [gcdc_flow.UpdateFlowRequest], + Awaitable[gcdc_flow.Flow]]: + r"""Return a callable for the update flow method over gRPC. + + Updates the specified flow. + + Returns: + Callable[[~.UpdateFlowRequest], + Awaitable[~.Flow]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_flow' not in self._stubs: + self._stubs['update_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/UpdateFlow', + request_serializer=gcdc_flow.UpdateFlowRequest.serialize, + response_deserializer=gcdc_flow.Flow.deserialize, + ) + return self._stubs['update_flow'] + + @property + def train_flow(self) -> Callable[ + [flow.TrainFlowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the train flow method over gRPC. + + Trains the specified flow. Note that only the flow in + 'draft' environment is trained. + + Returns: + Callable[[~.TrainFlowRequest], + 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_flow' not in self._stubs: + self._stubs['train_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/TrainFlow', + request_serializer=flow.TrainFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['train_flow'] + + @property + def validate_flow(self) -> Callable[ + [flow.ValidateFlowRequest], + Awaitable[flow.FlowValidationResult]]: + r"""Return a callable for the validate flow method over gRPC. + + Validates the specified flow and creates or updates + validation results. Please call this API after the + training is completed to get the complete validation + results. + + Returns: + Callable[[~.ValidateFlowRequest], + Awaitable[~.FlowValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'validate_flow' not in self._stubs: + self._stubs['validate_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/ValidateFlow', + request_serializer=flow.ValidateFlowRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['validate_flow'] + + @property + def get_flow_validation_result(self) -> Callable[ + [flow.GetFlowValidationResultRequest], + Awaitable[flow.FlowValidationResult]]: + r"""Return a callable for the get flow validation result method over gRPC. + + Gets the latest flow validation result. Flow + validation is performed when ValidateFlow is called. + + Returns: + Callable[[~.GetFlowValidationResultRequest], + Awaitable[~.FlowValidationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_flow_validation_result' not in self._stubs: + self._stubs['get_flow_validation_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/GetFlowValidationResult', + request_serializer=flow.GetFlowValidationResultRequest.serialize, + response_deserializer=flow.FlowValidationResult.deserialize, + ) + return self._stubs['get_flow_validation_result'] + + @property + def import_flow(self) -> Callable[ + [flow.ImportFlowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import flow method over gRPC. + + Imports the specified flow to the specified agent + from a binary file. + + Returns: + Callable[[~.ImportFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_flow' not in self._stubs: + self._stubs['import_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/ImportFlow', + request_serializer=flow.ImportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_flow'] + + @property + def export_flow(self) -> Callable[ + [flow.ExportFlowRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export flow method over gRPC. + + Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Returns: + Callable[[~.ExportFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'export_flow' not in self._stubs: + self._stubs['export_flow'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Flows/ExportFlow', + request_serializer=flow.ExportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_flow'] + + +__all__ = ( + 'FlowsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py new file mode 100644 index 00000000..8204500f --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py new file mode 100644 index 00000000..eee35c82 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py @@ -0,0 +1,580 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.intents import pagers +from google.cloud.dialogflowcx_v3beta1.types import intent +from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent +from google.protobuf import field_mask_pb2 # 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.cx.v3beta1.Intent]. + """ + + _client: IntentsClient + + DEFAULT_ENDPOINT = IntentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = IntentsClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(IntentsClient.entity_type_path) + parse_entity_type_path = staticmethod(IntentsClient.parse_entity_type_path) + intent_path = staticmethod(IntentsClient.intent_path) + parse_intent_path = staticmethod(IntentsClient.parse_intent_path) + common_billing_account_path = staticmethod(IntentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(IntentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(IntentsClient.common_folder_path) + parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) + common_organization_path = staticmethod(IntentsClient.common_organization_path) + parse_common_organization_path = staticmethod(IntentsClient.parse_common_organization_path) + common_project_path = staticmethod(IntentsClient.common_project_path) + parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) + common_location_path = staticmethod(IntentsClient.common_location_path) + parse_common_location_path = staticmethod(IntentsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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, + 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.dialogflowcx_v3beta1.types.ListIntentsRequest`): + The request object. The request message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.Intents.ListIntents]. + parent (:class:`str`): + Required. The agent to list all intents for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.intents.pagers.ListIntentsAsyncPager: + The response message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.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]) + if request is not 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 + + # 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, + 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.dialogflowcx_v3beta1.types.GetIntentRequest`): + The request object. The request message for + [Intents.GetIntent][google.cloud.dialogflow.cx.v3beta1.Intents.GetIntent]. + name (:class:`str`): + Required. The name of the intent. Format: + ``projects//locations//agents//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. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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.GetIntentRequest(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_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: gcdc_intent.CreateIntentRequest = None, + *, + parent: str = None, + intent: gcdc_intent.Intent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Creates an intent in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateIntentRequest`): + The request object. The request message for + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.CreateIntent]. + parent (:class:`str`): + Required. The agent to create an intent for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent (:class:`google.cloud.dialogflowcx_v3beta1.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. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_intent.CreateIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent is not None: + request.intent = intent + + # 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: gcdc_intent.UpdateIntentRequest = None, + *, + intent: gcdc_intent.Intent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Updates the specified intent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateIntentRequest`): + The request object. The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.UpdateIntent]. + intent (:class:`google.cloud.dialogflowcx_v3beta1.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`): + 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.dialogflowcx_v3beta1.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity 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]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_intent.UpdateIntentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intent is not None: + request.intent = intent + if update_mask is not None: + 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. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteIntentRequest`): + The request object. The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3beta1.Intents.DeleteIntent]. + name (:class:`str`): + Required. The name of the intent to delete. Format: + ``projects//locations//agents//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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "IntentsAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/client.py new file mode 100644 index 00000000..81957c73 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/client.py @@ -0,0 +1,776 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.intents import pagers +from google.cloud.dialogflowcx_v3beta1.types import intent +from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent +from google.protobuf import field_mask_pb2 # 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.cx.v3beta1.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 entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/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, + 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.dialogflowcx_v3beta1.types.ListIntentsRequest): + The request object. The request message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.Intents.ListIntents]. + parent (str): + Required. The agent to list all intents for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.intents.pagers.ListIntentsPager: + The response message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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 + + # 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, + 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.dialogflowcx_v3beta1.types.GetIntentRequest): + The request object. The request message for + [Intents.GetIntent][google.cloud.dialogflow.cx.v3beta1.Intents.GetIntent]. + name (str): + Required. The name of the intent. Format: + ``projects//locations//agents//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. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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.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 + + # 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: gcdc_intent.CreateIntentRequest = None, + *, + parent: str = None, + intent: gcdc_intent.Intent = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Creates an intent in the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateIntentRequest): + The request object. The request message for + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.CreateIntent]. + parent (str): + Required. The agent to create an intent for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + intent (google.cloud.dialogflowcx_v3beta1.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. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_intent.CreateIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_intent.CreateIntentRequest): + request = gcdc_intent.CreateIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if intent is not None: + request.intent = intent + + # 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: gcdc_intent.UpdateIntentRequest = None, + *, + intent: gcdc_intent.Intent = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_intent.Intent: + r"""Updates the specified intent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateIntentRequest): + The request object. The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.UpdateIntent]. + intent (google.cloud.dialogflowcx_v3beta1.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): + 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.dialogflowcx_v3beta1.types.Intent: + An intent represents a user's intent + to interact with a conversational agent. + You can provide information for the + Dialogflow API to use to match user + input to an intent by adding training + phrases (i.e., examples of user input) + to your intent. + + """ + # Create or coerce a protobuf request object. + # Sanity 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_intent.UpdateIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_intent.UpdateIntentRequest): + request = gcdc_intent.UpdateIntentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if intent is not None: + request.intent = intent + if update_mask is not None: + 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. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.DeleteIntentRequest): + The request object. The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3beta1.Intents.DeleteIntent]. + name (str): + Required. The name of the intent to delete. Format: + ``projects//locations//agents//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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "IntentsClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py new file mode 100644 index 00000000..ab57eb74 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.types import intent + + +class ListIntentsPager: + """A pager for iterating through ``list_intents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListIntentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListIntentsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py new file mode 100644 index 00000000..aa8039bb --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py new file mode 100644 index 00000000..46d79381 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/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.dialogflowcx_v3beta1.types import intent +from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent +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-dialogflowcx', + ).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, + ), + } + + @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[ + [gcdc_intent.CreateIntentRequest], + Union[ + gcdc_intent.Intent, + Awaitable[gcdc_intent.Intent] + ]]: + raise NotImplementedError() + + @property + def update_intent(self) -> Callable[ + [gcdc_intent.UpdateIntentRequest], + Union[ + gcdc_intent.Intent, + Awaitable[gcdc_intent.Intent] + ]]: + raise NotImplementedError() + + @property + def delete_intent(self) -> Callable[ + [intent.DeleteIntentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'IntentsTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py new file mode 100644 index 00000000..feeddaf7 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/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.dialogflowcx_v3beta1.types import intent +from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent +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.cx.v3beta1.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] = {} + + 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_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.cx.v3beta1.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.cx.v3beta1.Intents/GetIntent', + request_serializer=intent.GetIntentRequest.serialize, + response_deserializer=intent.Intent.deserialize, + ) + return self._stubs['get_intent'] + + @property + def create_intent(self) -> Callable[ + [gcdc_intent.CreateIntentRequest], + gcdc_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.cx.v3beta1.Intents/CreateIntent', + request_serializer=gcdc_intent.CreateIntentRequest.serialize, + response_deserializer=gcdc_intent.Intent.deserialize, + ) + return self._stubs['create_intent'] + + @property + def update_intent(self) -> Callable[ + [gcdc_intent.UpdateIntentRequest], + gcdc_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.cx.v3beta1.Intents/UpdateIntent', + request_serializer=gcdc_intent.UpdateIntentRequest.serialize, + response_deserializer=gcdc_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. + + 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.cx.v3beta1.Intents/DeleteIntent', + request_serializer=intent.DeleteIntentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_intent'] + + +__all__ = ( + 'IntentsGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py new file mode 100644 index 00000000..776d967c --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/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.dialogflowcx_v3beta1.types import intent +from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent +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.cx.v3beta1.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] = {} + + 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_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.cx.v3beta1.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.cx.v3beta1.Intents/GetIntent', + request_serializer=intent.GetIntentRequest.serialize, + response_deserializer=intent.Intent.deserialize, + ) + return self._stubs['get_intent'] + + @property + def create_intent(self) -> Callable[ + [gcdc_intent.CreateIntentRequest], + Awaitable[gcdc_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.cx.v3beta1.Intents/CreateIntent', + request_serializer=gcdc_intent.CreateIntentRequest.serialize, + response_deserializer=gcdc_intent.Intent.deserialize, + ) + return self._stubs['create_intent'] + + @property + def update_intent(self) -> Callable[ + [gcdc_intent.UpdateIntentRequest], + Awaitable[gcdc_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.cx.v3beta1.Intents/UpdateIntent', + request_serializer=gcdc_intent.UpdateIntentRequest.serialize, + response_deserializer=gcdc_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. + + 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.cx.v3beta1.Intents/DeleteIntent', + request_serializer=intent.DeleteIntentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_intent'] + + +__all__ = ( + 'IntentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py new file mode 100644 index 00000000..b8668f72 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/__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 PagesClient +from .async_client import PagesAsyncClient + +__all__ = ( + 'PagesClient', + 'PagesAsyncClient', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py new file mode 100644 index 00000000..bf55f0a9 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py @@ -0,0 +1,633 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.pages import pagers +from google.cloud.dialogflowcx_v3beta1.types import fulfillment +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport +from .client import PagesClient + + +class PagesAsyncClient: + """Service for managing + [Pages][google.cloud.dialogflow.cx.v3beta1.Page]. + """ + + _client: PagesClient + + DEFAULT_ENDPOINT = PagesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PagesClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(PagesClient.entity_type_path) + parse_entity_type_path = staticmethod(PagesClient.parse_entity_type_path) + flow_path = staticmethod(PagesClient.flow_path) + parse_flow_path = staticmethod(PagesClient.parse_flow_path) + intent_path = staticmethod(PagesClient.intent_path) + parse_intent_path = staticmethod(PagesClient.parse_intent_path) + page_path = staticmethod(PagesClient.page_path) + parse_page_path = staticmethod(PagesClient.parse_page_path) + transition_route_group_path = staticmethod(PagesClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(PagesClient.parse_transition_route_group_path) + webhook_path = staticmethod(PagesClient.webhook_path) + parse_webhook_path = staticmethod(PagesClient.parse_webhook_path) + common_billing_account_path = staticmethod(PagesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PagesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PagesClient.common_folder_path) + parse_common_folder_path = staticmethod(PagesClient.parse_common_folder_path) + common_organization_path = staticmethod(PagesClient.common_organization_path) + parse_common_organization_path = staticmethod(PagesClient.parse_common_organization_path) + common_project_path = staticmethod(PagesClient.common_project_path) + parse_common_project_path = staticmethod(PagesClient.parse_common_project_path) + common_location_path = staticmethod(PagesClient.common_location_path) + parse_common_location_path = staticmethod(PagesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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: + PagesAsyncClient: The constructed client. + """ + return PagesClient.from_service_account_info.__func__(PagesAsyncClient, 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: + PagesAsyncClient: The constructed client. + """ + return PagesClient.from_service_account_file.__func__(PagesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PagesTransport: + """Returns the transport used by the client instance. + + Returns: + PagesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PagesClient).get_transport_class, type(PagesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, PagesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the pages 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, ~.PagesTransport]): 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 = PagesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_pages(self, + request: page.ListPagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPagesAsyncPager: + r"""Returns the list of all pages in the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesRequest`): + The request object. The request message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. + parent (:class:`str`): + Required. The flow to list all pages for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.pages.pagers.ListPagesAsyncPager: + The response message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. + + 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 = page.ListPagesRequest(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_pages, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListPagesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_page(self, + request: page.GetPageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> page.Page: + r"""Retrieves the specified page. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetPageRequest`): + The request object. The request message for + [Pages.GetPage][google.cloud.dialogflow.cx.v3beta1.Pages.GetPage]. + name (:class:`str`): + Required. The name of the page. Format: + ``projects//locations//agents//flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = page.GetPageRequest(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_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_page(self, + request: gcdc_page.CreatePageRequest = None, + *, + parent: str = None, + page: gcdc_page.Page = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Creates a page in the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreatePageRequest`): + The request object. The request message for + [Pages.CreatePage][google.cloud.dialogflow.cx.v3beta1.Pages.CreatePage]. + parent (:class:`str`): + Required. The flow to create a page for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + page (:class:`google.cloud.dialogflowcx_v3beta1.types.Page`): + Required. The page to create. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, page]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_page.CreatePageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if page is not None: + request.page = page + + # 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_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_page(self, + request: gcdc_page.UpdatePageRequest = None, + *, + page: gcdc_page.Page = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Updates the specified page. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdatePageRequest`): + The request object. The request message for + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3beta1.Pages.UpdatePage]. + page (:class:`google.cloud.dialogflowcx_v3beta1.types.Page`): + Required. The page to update. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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.dialogflowcx_v3beta1.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([page, 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 = gcdc_page.UpdatePageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if page is not None: + request.page = page + if update_mask is not None: + 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_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("page.name", request.page.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_page(self, + request: page.DeletePageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified page. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeletePageRequest`): + The request object. The request message for + [Pages.DeletePage][google.cloud.dialogflow.cx.v3beta1.Pages.DeletePage]. + name (:class:`str`): + Required. The name of the page to delete. Format: + ``projects//locations//agents//Flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = page.DeletePageRequest(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_page, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PagesAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/client.py new file mode 100644 index 00000000..600b018a --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/client.py @@ -0,0 +1,865 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.pages import pagers +from google.cloud.dialogflowcx_v3beta1.types import fulfillment +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PagesGrpcTransport +from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport + + +class PagesClientMeta(type): + """Metaclass for the Pages 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[PagesTransport]] + _transport_registry["grpc"] = PagesGrpcTransport + _transport_registry["grpc_asyncio"] = PagesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[PagesTransport]: + """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 PagesClient(metaclass=PagesClientMeta): + """Service for managing + [Pages][google.cloud.dialogflow.cx.v3beta1.Page]. + """ + + @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: + PagesClient: 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: + PagesClient: 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) -> PagesTransport: + """Returns the transport used by the client instance. + + Returns: + PagesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, PagesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the pages 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, PagesTransport]): 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, PagesTransport): + # transport is a PagesTransport 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_pages(self, + request: page.ListPagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPagesPager: + r"""Returns the list of all pages in the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListPagesRequest): + The request object. The request message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. + parent (str): + Required. The flow to list all pages for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.pages.pagers.ListPagesPager: + The response message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. + + 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 page.ListPagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, page.ListPagesRequest): + request = page.ListPagesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_pages] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListPagesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_page(self, + request: page.GetPageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> page.Page: + r"""Retrieves the specified page. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetPageRequest): + The request object. The request message for + [Pages.GetPage][google.cloud.dialogflow.cx.v3beta1.Pages.GetPage]. + name (str): + Required. The name of the page. Format: + ``projects//locations//agents//flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 page.GetPageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, page.GetPageRequest): + request = page.GetPageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_page] + + # Certain fields should be provided 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_page(self, + request: gcdc_page.CreatePageRequest = None, + *, + parent: str = None, + page: gcdc_page.Page = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Creates a page in the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreatePageRequest): + The request object. The request message for + [Pages.CreatePage][google.cloud.dialogflow.cx.v3beta1.Pages.CreatePage]. + parent (str): + Required. The flow to create a page for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + page (google.cloud.dialogflowcx_v3beta1.types.Page): + Required. The page to create. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, page]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_page.CreatePageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_page.CreatePageRequest): + request = gcdc_page.CreatePageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if page is not None: + request.page = page + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_page] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_page(self, + request: gcdc_page.UpdatePageRequest = None, + *, + page: gcdc_page.Page = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_page.Page: + r"""Updates the specified page. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdatePageRequest): + The request object. The request message for + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3beta1.Pages.UpdatePage]. + page (google.cloud.dialogflowcx_v3beta1.types.Page): + Required. The page to update. + This corresponds to the ``page`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.dialogflowcx_v3beta1.types.Page: + A Dialogflow CX conversation (session) can be described and visualized as a + state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your + combined pages can handle a complete conversation on + the topics the flow is designed for. At any given + moment, exactly one page is the current page, the + current page is considered active, and the flow + associated with that page is considered active. Every + flow has a special start page. When a flow initially + becomes active, the start page page becomes the + current page. For each conversational turn, the + current page will either stay the same or transition + to another page. + + You configure each page to collect information from + the end-user that is relevant for the conversational + state represented by the page. + + For more information, see the [Page + guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([page, 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 gcdc_page.UpdatePageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_page.UpdatePageRequest): + request = gcdc_page.UpdatePageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if page is not None: + request.page = page + if update_mask is not None: + 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_page] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("page.name", request.page.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_page(self, + request: page.DeletePageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified page. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.DeletePageRequest): + The request object. The request message for + [Pages.DeletePage][google.cloud.dialogflow.cx.v3beta1.Pages.DeletePage]. + name (str): + Required. The name of the page to delete. Format: + ``projects//locations//agents//Flows//pages/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 page.DeletePageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, page.DeletePageRequest): + request = page.DeletePageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_page] + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "PagesClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py new file mode 100644 index 00000000..974940d5 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/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.dialogflowcx_v3beta1.types import page + + +class ListPagesPager: + """A pager for iterating through ``list_pages`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``pages`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPages`` requests and continue to iterate + through the ``pages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse` + 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[..., page.ListPagesResponse], + request: page.ListPagesRequest, + response: page.ListPagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListPagesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse): + 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 = page.ListPagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[page.ListPagesResponse]: + 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[page.Page]: + for page in self.pages: + yield from page.pages + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPagesAsyncPager: + """A pager for iterating through ``list_pages`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``pages`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPages`` requests and continue to iterate + through the ``pages`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse` + 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[page.ListPagesResponse]], + request: page.ListPagesRequest, + response: page.ListPagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListPagesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse): + 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 = page.ListPagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[page.ListPagesResponse]: + 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[page.Page]: + async def async_generator(): + async for page in self.pages: + for response in page.pages: + 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py new file mode 100644 index 00000000..ee74f029 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/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 PagesTransport +from .grpc import PagesGrpcTransport +from .grpc_asyncio import PagesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PagesTransport]] +_transport_registry['grpc'] = PagesGrpcTransport +_transport_registry['grpc_asyncio'] = PagesGrpcAsyncIOTransport + +__all__ = ( + 'PagesTransport', + 'PagesGrpcTransport', + 'PagesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py new file mode 100644 index 00000000..ee8147bf --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/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.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page +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-dialogflowcx', + ).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 PagesTransport(abc.ABC): + """Abstract transport class for Pages.""" + + 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_pages: gapic_v1.method.wrap_method( + self.list_pages, + default_timeout=None, + client_info=client_info, + ), + self.get_page: gapic_v1.method.wrap_method( + self.get_page, + default_timeout=None, + client_info=client_info, + ), + self.create_page: gapic_v1.method.wrap_method( + self.create_page, + default_timeout=None, + client_info=client_info, + ), + self.update_page: gapic_v1.method.wrap_method( + self.update_page, + default_timeout=None, + client_info=client_info, + ), + self.delete_page: gapic_v1.method.wrap_method( + self.delete_page, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_pages(self) -> Callable[ + [page.ListPagesRequest], + Union[ + page.ListPagesResponse, + Awaitable[page.ListPagesResponse] + ]]: + raise NotImplementedError() + + @property + def get_page(self) -> Callable[ + [page.GetPageRequest], + Union[ + page.Page, + Awaitable[page.Page] + ]]: + raise NotImplementedError() + + @property + def create_page(self) -> Callable[ + [gcdc_page.CreatePageRequest], + Union[ + gcdc_page.Page, + Awaitable[gcdc_page.Page] + ]]: + raise NotImplementedError() + + @property + def update_page(self) -> Callable[ + [gcdc_page.UpdatePageRequest], + Union[ + gcdc_page.Page, + Awaitable[gcdc_page.Page] + ]]: + raise NotImplementedError() + + @property + def delete_page(self) -> Callable[ + [page.DeletePageRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'PagesTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py new file mode 100644 index 00000000..2f85f709 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py @@ -0,0 +1,355 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page +from google.protobuf import empty_pb2 # type: ignore +from .base import PagesTransport, DEFAULT_CLIENT_INFO + + +class PagesGrpcTransport(PagesTransport): + """gRPC backend transport for Pages. + + Service for managing + [Pages][google.cloud.dialogflow.cx.v3beta1.Page]. + + 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_pages(self) -> Callable[ + [page.ListPagesRequest], + page.ListPagesResponse]: + r"""Return a callable for the list pages method over gRPC. + + Returns the list of all pages in the specified flow. + + Returns: + Callable[[~.ListPagesRequest], + ~.ListPagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_pages' not in self._stubs: + self._stubs['list_pages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Pages/ListPages', + request_serializer=page.ListPagesRequest.serialize, + response_deserializer=page.ListPagesResponse.deserialize, + ) + return self._stubs['list_pages'] + + @property + def get_page(self) -> Callable[ + [page.GetPageRequest], + page.Page]: + r"""Return a callable for the get page method over gRPC. + + Retrieves the specified page. + + Returns: + Callable[[~.GetPageRequest], + ~.Page]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_page' not in self._stubs: + self._stubs['get_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Pages/GetPage', + request_serializer=page.GetPageRequest.serialize, + response_deserializer=page.Page.deserialize, + ) + return self._stubs['get_page'] + + @property + def create_page(self) -> Callable[ + [gcdc_page.CreatePageRequest], + gcdc_page.Page]: + r"""Return a callable for the create page method over gRPC. + + Creates a page in the specified flow. + + Returns: + Callable[[~.CreatePageRequest], + ~.Page]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_page' not in self._stubs: + self._stubs['create_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Pages/CreatePage', + request_serializer=gcdc_page.CreatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['create_page'] + + @property + def update_page(self) -> Callable[ + [gcdc_page.UpdatePageRequest], + gcdc_page.Page]: + r"""Return a callable for the update page method over gRPC. + + Updates the specified page. + + Returns: + Callable[[~.UpdatePageRequest], + ~.Page]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_page' not in self._stubs: + self._stubs['update_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Pages/UpdatePage', + request_serializer=gcdc_page.UpdatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['update_page'] + + @property + def delete_page(self) -> Callable[ + [page.DeletePageRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete page method over gRPC. + + Deletes the specified page. + + Returns: + Callable[[~.DeletePageRequest], + ~.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_page' not in self._stubs: + self._stubs['delete_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Pages/DeletePage', + request_serializer=page.DeletePageRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_page'] + + +__all__ = ( + 'PagesGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py new file mode 100644 index 00000000..cc5e44df --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py @@ -0,0 +1,359 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page +from google.protobuf import empty_pb2 # type: ignore +from .base import PagesTransport, DEFAULT_CLIENT_INFO +from .grpc import PagesGrpcTransport + + +class PagesGrpcAsyncIOTransport(PagesTransport): + """gRPC AsyncIO backend transport for Pages. + + Service for managing + [Pages][google.cloud.dialogflow.cx.v3beta1.Page]. + + 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_pages(self) -> Callable[ + [page.ListPagesRequest], + Awaitable[page.ListPagesResponse]]: + r"""Return a callable for the list pages method over gRPC. + + Returns the list of all pages in the specified flow. + + Returns: + Callable[[~.ListPagesRequest], + Awaitable[~.ListPagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_pages' not in self._stubs: + self._stubs['list_pages'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Pages/ListPages', + request_serializer=page.ListPagesRequest.serialize, + response_deserializer=page.ListPagesResponse.deserialize, + ) + return self._stubs['list_pages'] + + @property + def get_page(self) -> Callable[ + [page.GetPageRequest], + Awaitable[page.Page]]: + r"""Return a callable for the get page method over gRPC. + + Retrieves the specified page. + + Returns: + Callable[[~.GetPageRequest], + Awaitable[~.Page]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_page' not in self._stubs: + self._stubs['get_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Pages/GetPage', + request_serializer=page.GetPageRequest.serialize, + response_deserializer=page.Page.deserialize, + ) + return self._stubs['get_page'] + + @property + def create_page(self) -> Callable[ + [gcdc_page.CreatePageRequest], + Awaitable[gcdc_page.Page]]: + r"""Return a callable for the create page method over gRPC. + + Creates a page in the specified flow. + + Returns: + Callable[[~.CreatePageRequest], + Awaitable[~.Page]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_page' not in self._stubs: + self._stubs['create_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Pages/CreatePage', + request_serializer=gcdc_page.CreatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['create_page'] + + @property + def update_page(self) -> Callable[ + [gcdc_page.UpdatePageRequest], + Awaitable[gcdc_page.Page]]: + r"""Return a callable for the update page method over gRPC. + + Updates the specified page. + + Returns: + Callable[[~.UpdatePageRequest], + Awaitable[~.Page]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_page' not in self._stubs: + self._stubs['update_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Pages/UpdatePage', + request_serializer=gcdc_page.UpdatePageRequest.serialize, + response_deserializer=gcdc_page.Page.deserialize, + ) + return self._stubs['update_page'] + + @property + def delete_page(self) -> Callable[ + [page.DeletePageRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete page method over gRPC. + + Deletes the specified page. + + Returns: + Callable[[~.DeletePageRequest], + 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_page' not in self._stubs: + self._stubs['delete_page'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Pages/DeletePage', + request_serializer=page.DeletePageRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_page'] + + +__all__ = ( + 'PagesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py new file mode 100644 index 00000000..292d96e7 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__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 SecuritySettingsServiceClient +from .async_client import SecuritySettingsServiceAsyncClient + +__all__ = ( + 'SecuritySettingsServiceClient', + 'SecuritySettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py new file mode 100644 index 00000000..b2dd0a48 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.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. +# +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.dialogflowcx_v3beta1.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport +from .client import SecuritySettingsServiceClient + + +class SecuritySettingsServiceAsyncClient: + """Service for managing security settings for Dialogflow.""" + + _client: SecuritySettingsServiceClient + + DEFAULT_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_MTLS_ENDPOINT + + security_settings_path = staticmethod(SecuritySettingsServiceClient.security_settings_path) + parse_security_settings_path = staticmethod(SecuritySettingsServiceClient.parse_security_settings_path) + common_billing_account_path = staticmethod(SecuritySettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecuritySettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecuritySettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SecuritySettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SecuritySettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SecuritySettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SecuritySettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(SecuritySettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(SecuritySettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(SecuritySettingsServiceClient.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: + SecuritySettingsServiceAsyncClient: The constructed client. + """ + return SecuritySettingsServiceClient.from_service_account_info.__func__(SecuritySettingsServiceAsyncClient, 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: + SecuritySettingsServiceAsyncClient: The constructed client. + """ + return SecuritySettingsServiceClient.from_service_account_file.__func__(SecuritySettingsServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SecuritySettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SecuritySettingsServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SecuritySettingsServiceClient).get_transport_class, type(SecuritySettingsServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SecuritySettingsServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security settings service 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, ~.SecuritySettingsServiceTransport]): 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 = SecuritySettingsServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_security_settings(self, + request: gcdc_security_settings.CreateSecuritySettingsRequest = None, + *, + parent: str = None, + security_settings: gcdc_security_settings.SecuritySettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Create security settings in the specified location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.CreateSecuritySettings][]. + parent (:class:`str`): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_settings (:class:`google.cloud.dialogflowcx_v3beta1.types.SecuritySettings`): + Required. The security settings to + create. + + This corresponds to the ``security_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, security_settings]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_security_settings.CreateSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_settings is not None: + request.security_settings = security_settings + + # 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_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_security_settings(self, + request: security_settings.GetSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_settings.SecuritySettings: + r"""Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.GetSecuritySettings]. + name (:class:`str`): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = security_settings.GetSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_security_settings(self, + request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, + *, + security_settings: gcdc_security_settings.SecuritySettings = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings]. + security_settings (:class:`google.cloud.dialogflowcx_v3beta1.types.SecuritySettings`): + Required. [SecuritySettings] object that contains values + for each of the fields to update. + + This corresponds to the ``security_settings`` 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.dialogflowcx_v3beta1.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_settings, 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 = gcdc_security_settings.UpdateSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_settings is not None: + request.security_settings = security_settings + if update_mask is not None: + 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_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_settings.name", request.security_settings.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_security_settings(self, + request: security_settings.ListSecuritySettingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecuritySettingsAsyncPager: + r"""Returns the list of all security settings in the + specified location. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.ListSecuritySettings][]. + parent (:class:`str`): + Required. The location to list all security settings + 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.dialogflowcx_v3beta1.services.security_settings_service.pagers.ListSecuritySettingsAsyncPager: + The response message for + [SecuritySettings.ListSecuritySettings][]. + + 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 = security_settings.ListSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListSecuritySettingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_security_settings(self, + request: security_settings.DeleteSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteSecuritySettingsRequest`): + The request object. The request message for + [SecuritySettings.DeleteSecuritySettings][]. + name (:class:`str`): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = security_settings.DeleteSecuritySettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_security_settings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecuritySettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py new file mode 100644 index 00000000..502cfcc3 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/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 +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.dialogflowcx_v3beta1.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecuritySettingsServiceGrpcTransport +from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport + + +class SecuritySettingsServiceClientMeta(type): + """Metaclass for the SecuritySettingsService 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[SecuritySettingsServiceTransport]] + _transport_registry["grpc"] = SecuritySettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SecuritySettingsServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SecuritySettingsServiceTransport]: + """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 SecuritySettingsServiceClient(metaclass=SecuritySettingsServiceClientMeta): + """Service for managing security settings for Dialogflow.""" + + @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: + SecuritySettingsServiceClient: 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: + SecuritySettingsServiceClient: 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) -> SecuritySettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SecuritySettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def security_settings_path(project: str,location: str,security_settings: str,) -> str: + """Returns a fully-qualified security_settings string.""" + return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + + @staticmethod + def parse_security_settings_path(path: str) -> Dict[str,str]: + """Parses a security_settings path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def 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, SecuritySettingsServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security settings service 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, SecuritySettingsServiceTransport]): 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, SecuritySettingsServiceTransport): + # transport is a SecuritySettingsServiceTransport 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_security_settings(self, + request: gcdc_security_settings.CreateSecuritySettingsRequest = None, + *, + parent: str = None, + security_settings: gcdc_security_settings.SecuritySettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Create security settings in the specified location. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateSecuritySettingsRequest): + The request object. The request message for + [SecuritySettings.CreateSecuritySettings][]. + parent (str): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + for. Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + security_settings (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings): + Required. The security settings to + create. + + This corresponds to the ``security_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, security_settings]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_security_settings.CreateSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_security_settings.CreateSecuritySettingsRequest): + request = gcdc_security_settings.CreateSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if security_settings is not None: + request.security_settings = security_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_security_settings(self, + request: security_settings.GetSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> security_settings.SecuritySettings: + r"""Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetSecuritySettingsRequest): + The request object. The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.GetSecuritySettings]. + name (str): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 security_settings.GetSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.GetSecuritySettingsRequest): + request = security_settings.GetSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_security_settings] + + # Certain fields should be provided 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_security_settings(self, + request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, + *, + security_settings: gcdc_security_settings.SecuritySettings = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_security_settings.SecuritySettings: + r"""Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateSecuritySettingsRequest): + The request object. The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings]. + security_settings (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings): + Required. [SecuritySettings] object that contains values + for each of the fields to update. + + This corresponds to the ``security_settings`` 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.dialogflowcx_v3beta1.types.SecuritySettings: + Represents the settings related to + security issues, such as data redaction + and data retention. It may take hours + for updates on the settings to propagate + to all the related components and take + effect. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_settings, 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 gcdc_security_settings.UpdateSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_security_settings.UpdateSecuritySettingsRequest): + request = gcdc_security_settings.UpdateSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_settings is not None: + request.security_settings = security_settings + if update_mask is not None: + 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_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_settings.name", request.security_settings.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_security_settings(self, + request: security_settings.ListSecuritySettingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSecuritySettingsPager: + r"""Returns the list of all security settings in the + specified location. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsRequest): + The request object. The request message for + [SecuritySettings.ListSecuritySettings][]. + parent (str): + Required. The location to list all security settings + 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.dialogflowcx_v3beta1.services.security_settings_service.pagers.ListSecuritySettingsPager: + The response message for + [SecuritySettings.ListSecuritySettings][]. + + 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 security_settings.ListSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.ListSecuritySettingsRequest): + request = security_settings.ListSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_security_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListSecuritySettingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_security_settings(self, + request: security_settings.DeleteSecuritySettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.DeleteSecuritySettingsRequest): + The request object. The request message for + [SecuritySettings.DeleteSecuritySettings][]. + name (str): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 security_settings.DeleteSecuritySettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, security_settings.DeleteSecuritySettingsRequest): + request = security_settings.DeleteSecuritySettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_security_settings] + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecuritySettingsServiceClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py new file mode 100644 index 00000000..040993a7 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/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.dialogflowcx_v3beta1.types import security_settings + + +class ListSecuritySettingsPager: + """A pager for iterating through ``list_security_settings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``security_settings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSecuritySettings`` requests and continue to iterate + through the ``security_settings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse` + 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[..., security_settings.ListSecuritySettingsResponse], + request: security_settings.ListSecuritySettingsRequest, + response: security_settings.ListSecuritySettingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse): + 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 = security_settings.ListSecuritySettingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[security_settings.ListSecuritySettingsResponse]: + 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[security_settings.SecuritySettings]: + for page in self.pages: + yield from page.security_settings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSecuritySettingsAsyncPager: + """A pager for iterating through ``list_security_settings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``security_settings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSecuritySettings`` requests and continue to iterate + through the ``security_settings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse` + 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[security_settings.ListSecuritySettingsResponse]], + request: security_settings.ListSecuritySettingsRequest, + response: security_settings.ListSecuritySettingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse): + 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 = security_settings.ListSecuritySettingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[security_settings.ListSecuritySettingsResponse]: + 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[security_settings.SecuritySettings]: + async def async_generator(): + async for page in self.pages: + for response in page.security_settings: + 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py new file mode 100644 index 00000000..116b7680 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/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 SecuritySettingsServiceTransport +from .grpc import SecuritySettingsServiceGrpcTransport +from .grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecuritySettingsServiceTransport]] +_transport_registry['grpc'] = SecuritySettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SecuritySettingsServiceGrpcAsyncIOTransport + +__all__ = ( + 'SecuritySettingsServiceTransport', + 'SecuritySettingsServiceGrpcTransport', + 'SecuritySettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py new file mode 100644 index 00000000..552d4b3a --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/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.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class SecuritySettingsServiceTransport(abc.ABC): + """Abstract transport class for SecuritySettingsService.""" + + 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_security_settings: gapic_v1.method.wrap_method( + self.create_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_security_settings: gapic_v1.method.wrap_method( + self.get_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_security_settings: gapic_v1.method.wrap_method( + self.update_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.list_security_settings: gapic_v1.method.wrap_method( + self.list_security_settings, + default_timeout=None, + client_info=client_info, + ), + self.delete_security_settings: gapic_v1.method.wrap_method( + self.delete_security_settings, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def create_security_settings(self) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + Union[ + gcdc_security_settings.SecuritySettings, + Awaitable[gcdc_security_settings.SecuritySettings] + ]]: + raise NotImplementedError() + + @property + def get_security_settings(self) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + Union[ + security_settings.SecuritySettings, + Awaitable[security_settings.SecuritySettings] + ]]: + raise NotImplementedError() + + @property + def update_security_settings(self) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + Union[ + gcdc_security_settings.SecuritySettings, + Awaitable[gcdc_security_settings.SecuritySettings] + ]]: + raise NotImplementedError() + + @property + def list_security_settings(self) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + Union[ + security_settings.ListSecuritySettingsResponse, + Awaitable[security_settings.ListSecuritySettingsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_security_settings(self) -> Callable[ + [security_settings.DeleteSecuritySettingsRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SecuritySettingsServiceTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py new file mode 100644 index 00000000..59688392 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py @@ -0,0 +1,359 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings +from google.protobuf import empty_pb2 # type: ignore +from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO + + +class SecuritySettingsServiceGrpcTransport(SecuritySettingsServiceTransport): + """gRPC backend transport for SecuritySettingsService. + + Service for managing security settings for Dialogflow. + + 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_security_settings(self) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + gcdc_security_settings.SecuritySettings]: + r"""Return a callable for the create security settings method over gRPC. + + Create security settings in the specified location. + + Returns: + Callable[[~.CreateSecuritySettingsRequest], + ~.SecuritySettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_settings' not in self._stubs: + self._stubs['create_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/CreateSecuritySettings', + request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['create_security_settings'] + + @property + def get_security_settings(self) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + security_settings.SecuritySettings]: + r"""Return a callable for the get security settings method over gRPC. + + Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Returns: + Callable[[~.GetSecuritySettingsRequest], + ~.SecuritySettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_security_settings' not in self._stubs: + self._stubs['get_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/GetSecuritySettings', + request_serializer=security_settings.GetSecuritySettingsRequest.serialize, + response_deserializer=security_settings.SecuritySettings.deserialize, + ) + return self._stubs['get_security_settings'] + + @property + def update_security_settings(self) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + gcdc_security_settings.SecuritySettings]: + r"""Return a callable for the update security settings method over gRPC. + + Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Returns: + Callable[[~.UpdateSecuritySettingsRequest], + ~.SecuritySettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_settings' not in self._stubs: + self._stubs['update_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/UpdateSecuritySettings', + request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['update_security_settings'] + + @property + def list_security_settings(self) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + security_settings.ListSecuritySettingsResponse]: + r"""Return a callable for the list security settings method over gRPC. + + Returns the list of all security settings in the + specified location. + + Returns: + Callable[[~.ListSecuritySettingsRequest], + ~.ListSecuritySettingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_security_settings' not in self._stubs: + self._stubs['list_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/ListSecuritySettings', + request_serializer=security_settings.ListSecuritySettingsRequest.serialize, + response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, + ) + return self._stubs['list_security_settings'] + + @property + def delete_security_settings(self) -> Callable[ + [security_settings.DeleteSecuritySettingsRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete security settings method over gRPC. + + Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Returns: + Callable[[~.DeleteSecuritySettingsRequest], + ~.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_security_settings' not in self._stubs: + self._stubs['delete_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/DeleteSecuritySettings', + request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_security_settings'] + + +__all__ = ( + 'SecuritySettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..aa3458ca --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,363 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import 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.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings +from google.protobuf import empty_pb2 # type: ignore +from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SecuritySettingsServiceGrpcTransport + + +class SecuritySettingsServiceGrpcAsyncIOTransport(SecuritySettingsServiceTransport): + """gRPC AsyncIO backend transport for SecuritySettingsService. + + Service for managing security settings for Dialogflow. + + 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_security_settings(self) -> Callable[ + [gcdc_security_settings.CreateSecuritySettingsRequest], + Awaitable[gcdc_security_settings.SecuritySettings]]: + r"""Return a callable for the create security settings method over gRPC. + + Create security settings in the specified location. + + Returns: + Callable[[~.CreateSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_settings' not in self._stubs: + self._stubs['create_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/CreateSecuritySettings', + request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['create_security_settings'] + + @property + def get_security_settings(self) -> Callable[ + [security_settings.GetSecuritySettingsRequest], + Awaitable[security_settings.SecuritySettings]]: + r"""Return a callable for the get security settings method over gRPC. + + Retrieves the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + The returned settings may be stale by up to 1 minute. + + Returns: + Callable[[~.GetSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_security_settings' not in self._stubs: + self._stubs['get_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/GetSecuritySettings', + request_serializer=security_settings.GetSecuritySettingsRequest.serialize, + response_deserializer=security_settings.SecuritySettings.deserialize, + ) + return self._stubs['get_security_settings'] + + @property + def update_security_settings(self) -> Callable[ + [gcdc_security_settings.UpdateSecuritySettingsRequest], + Awaitable[gcdc_security_settings.SecuritySettings]]: + r"""Return a callable for the update security settings method over gRPC. + + Updates the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Returns: + Callable[[~.UpdateSecuritySettingsRequest], + Awaitable[~.SecuritySettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_settings' not in self._stubs: + self._stubs['update_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/UpdateSecuritySettings', + request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, + response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, + ) + return self._stubs['update_security_settings'] + + @property + def list_security_settings(self) -> Callable[ + [security_settings.ListSecuritySettingsRequest], + Awaitable[security_settings.ListSecuritySettingsResponse]]: + r"""Return a callable for the list security settings method over gRPC. + + Returns the list of all security settings in the + specified location. + + Returns: + Callable[[~.ListSecuritySettingsRequest], + Awaitable[~.ListSecuritySettingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_security_settings' not in self._stubs: + self._stubs['list_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/ListSecuritySettings', + request_serializer=security_settings.ListSecuritySettingsRequest.serialize, + response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, + ) + return self._stubs['list_security_settings'] + + @property + def delete_security_settings(self) -> Callable[ + [security_settings.DeleteSecuritySettingsRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete security settings method over gRPC. + + Deletes the specified + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. + + Returns: + Callable[[~.DeleteSecuritySettingsRequest], + 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_security_settings' not in self._stubs: + self._stubs['delete_security_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/DeleteSecuritySettings', + request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_security_settings'] + + +__all__ = ( + 'SecuritySettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py new file mode 100644 index 00000000..fb6678b1 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py new file mode 100644 index 00000000..c410c4d4 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py @@ -0,0 +1,635 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.session_entity_types import pagers +from google.cloud.dialogflowcx_v3beta1.types import entity_type +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_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.cx.v3beta1.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. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest`): + The request object. The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.ListSessionEntityTypes]. + parent (:class:`str`): + Required. The session to list all session entity types + from. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager: + The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.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. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.GetSessionEntityType]. + name (:class:`str`): + Required. The name of the session entity type. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3beta1.EntityType] + at the user session level (we refer to the entity + types defined at the agent level as "custom entity + types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not 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: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, + *, + parent: str = None, + session_entity_type: gcdc_session_entity_type.SessionEntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Creates a session entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.CreateSessionEntityType]. + parent (:class:`str`): + Required. The session to create a session entity type + for. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + 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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3beta1.EntityType] + at the user session level (we refer to the entity + types defined at the agent level as "custom entity + types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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, 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 = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session_entity_type is not None: + 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: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, + *, + session_entity_type: gcdc_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]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Updates the specified session entity type. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.UpdateSessionEntityType]. + session_entity_type (:class:`google.cloud.dialogflowcx_v3beta1.types.SessionEntityType`): + Required. The session entity type to update. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + 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`): + 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.dialogflowcx_v3beta1.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3beta1.EntityType] + at the user session level (we refer to the entity + types defined at the agent level as "custom entity + types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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([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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session_entity_type is not None: + request.session_entity_type = session_entity_type + if update_mask is not None: + 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. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteSessionEntityTypeRequest`): + The request object. The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.DeleteSessionEntityType]. + name (:class:`str`): + Required. The name of the session entity type to delete. + Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionEntityTypesAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py new file mode 100644 index 00000000..8445e990 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py @@ -0,0 +1,822 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.session_entity_types import pagers +from google.cloud.dialogflowcx_v3beta1.types import entity_type +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_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.cx.v3beta1.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,location: str,agent: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, 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.+?)/locations/(?P.+?)/agents/(?P.+?)/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. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest): + The request object. The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.ListSessionEntityTypes]. + parent (str): + Required. The session to list all session entity types + from. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.session_entity_types.pagers.ListSessionEntityTypesPager: + The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.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. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetSessionEntityTypeRequest): + The request object. The request message for + [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.GetSessionEntityType]. + name (str): + Required. The name of the session entity type. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3beta1.EntityType] + at the user session level (we refer to the entity + types defined at the agent level as "custom entity + types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, + *, + parent: str = None, + session_entity_type: gcdc_session_entity_type.SessionEntityType = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Creates a session entity type. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateSessionEntityTypeRequest): + The request object. The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.CreateSessionEntityType]. + parent (str): + Required. The session to create a session entity type + for. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + session_entity_type (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3beta1.EntityType] + at the user session level (we refer to the entity + types defined at the agent level as "custom entity + types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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, 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 gcdc_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, gcdc_session_entity_type.CreateSessionEntityTypeRequest): + request = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if session_entity_type is not None: + 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: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, + *, + session_entity_type: gcdc_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]] = (), + ) -> gcdc_session_entity_type.SessionEntityType: + r"""Updates the specified session entity type. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateSessionEntityTypeRequest): + The request object. The request message for + [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.UpdateSessionEntityType]. + session_entity_type (google.cloud.dialogflowcx_v3beta1.types.SessionEntityType): + Required. The session entity type to update. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + 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): + 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.dialogflowcx_v3beta1.types.SessionEntityType: + Session entity types are referred to as **User** entity types and are + entities that are built for an individual user such + as favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session + level to extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3beta1.EntityType] + at the user session level (we refer to the entity + types defined at the agent level as "custom entity + types"). + + Note: session entity types apply to all queries, + regardless of the language. + + For more information about entity types, see the + [Dialogflow + documentation](\ 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([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 gcdc_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, gcdc_session_entity_type.UpdateSessionEntityTypeRequest): + request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if session_entity_type is not None: + request.session_entity_type = session_entity_type + if update_mask is not None: + 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. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.DeleteSessionEntityTypeRequest): + The request object. The request message for + [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.DeleteSessionEntityType]. + name (str): + Required. The name of the session entity type to delete. + Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume + default 'draft' environment. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionEntityTypesClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py new file mode 100644 index 00000000..c51702a3 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py new file mode 100644 index 00000000..fee52672 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py new file mode 100644 index 00000000..7aa63002 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.types import session_entity_type +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +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[ + [gcdc_session_entity_type.CreateSessionEntityTypeRequest], + Union[ + gcdc_session_entity_type.SessionEntityType, + Awaitable[gcdc_session_entity_type.SessionEntityType] + ]]: + raise NotImplementedError() + + @property + def update_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], + Union[ + gcdc_session_entity_type.SessionEntityType, + Awaitable[gcdc_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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py new file mode 100644 index 00000000..c2eedab0 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/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.dialogflowcx_v3beta1.types import session_entity_type +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import empty_pb2 # type: ignore +from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO + + +class SessionEntityTypesGrpcTransport(SessionEntityTypesTransport): + """gRPC backend transport for SessionEntityTypes. + + Service for managing + [SessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.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. + + 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.cx.v3beta1.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. + + 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.cx.v3beta1.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[ + [gcdc_session_entity_type.CreateSessionEntityTypeRequest], + gcdc_session_entity_type.SessionEntityType]: + r"""Return a callable for the create session entity type method over gRPC. + + Creates a session entity type. + + 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.cx.v3beta1.SessionEntityTypes/CreateSessionEntityType', + request_serializer=gcdc_session_entity_type.CreateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['create_session_entity_type'] + + @property + def update_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], + gcdc_session_entity_type.SessionEntityType]: + r"""Return a callable for the update session entity type method over gRPC. + + Updates the specified session entity type. + + 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.cx.v3beta1.SessionEntityTypes/UpdateSessionEntityType', + request_serializer=gcdc_session_entity_type.UpdateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_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. + + 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.cx.v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py new file mode 100644 index 00000000..357754dd --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/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.dialogflowcx_v3beta1.types import session_entity_type +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_session_entity_type +from google.protobuf import empty_pb2 # 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.cx.v3beta1.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. + + 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.cx.v3beta1.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. + + 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.cx.v3beta1.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[ + [gcdc_session_entity_type.CreateSessionEntityTypeRequest], + Awaitable[gcdc_session_entity_type.SessionEntityType]]: + r"""Return a callable for the create session entity type method over gRPC. + + Creates a session entity type. + + 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.cx.v3beta1.SessionEntityTypes/CreateSessionEntityType', + request_serializer=gcdc_session_entity_type.CreateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, + ) + return self._stubs['create_session_entity_type'] + + @property + def update_session_entity_type(self) -> Callable[ + [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], + Awaitable[gcdc_session_entity_type.SessionEntityType]]: + r"""Return a callable for the update session entity type method over gRPC. + + Updates the specified session entity type. + + 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.cx.v3beta1.SessionEntityTypes/UpdateSessionEntityType', + request_serializer=gcdc_session_entity_type.UpdateSessionEntityTypeRequest.serialize, + response_deserializer=gcdc_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. + + 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.cx.v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py new file mode 100644 index 00000000..92490cc5 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py new file mode 100644 index 00000000..e6fcf7ba --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py @@ -0,0 +1,460 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.types import audio_config +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import session +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport +from .client import SessionsClient + + +class SessionsAsyncClient: + """A session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.DetectIntent] + method to determine user intent and respond. + """ + + _client: SessionsClient + + DEFAULT_ENDPOINT = SessionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SessionsClient.DEFAULT_MTLS_ENDPOINT + + entity_type_path = staticmethod(SessionsClient.entity_type_path) + parse_entity_type_path = staticmethod(SessionsClient.parse_entity_type_path) + flow_path = staticmethod(SessionsClient.flow_path) + parse_flow_path = staticmethod(SessionsClient.parse_flow_path) + intent_path = staticmethod(SessionsClient.intent_path) + parse_intent_path = staticmethod(SessionsClient.parse_intent_path) + page_path = staticmethod(SessionsClient.page_path) + parse_page_path = staticmethod(SessionsClient.parse_page_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) + transition_route_group_path = staticmethod(SessionsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(SessionsClient.parse_transition_route_group_path) + webhook_path = staticmethod(SessionsClient.webhook_path) + parse_webhook_path = staticmethod(SessionsClient.parse_webhook_path) + common_billing_account_path = staticmethod(SessionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SessionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SessionsClient.common_folder_path) + parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) + common_organization_path = staticmethod(SessionsClient.common_organization_path) + parse_common_organization_path = staticmethod(SessionsClient.parse_common_organization_path) + common_project_path = staticmethod(SessionsClient.common_project_path) + parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) + common_location_path = staticmethod(SessionsClient.common_location_path) + parse_common_location_path = staticmethod(SessionsClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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: session.DetectIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> 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 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.dialogflowcx_v3beta1.types.DetectIntentRequest`): + The request object. The request to detect user's intent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.DetectIntentResponse: + The message returned from the + DetectIntent method. + + """ + # Create or coerce a protobuf request object. + request = session.DetectIntentRequest(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.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.dialogflowcx_v3beta1.types.StreamingDetectIntentRequest`]): + The request object AsyncIterator. The top-level message sent by the + client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.StreamingDetectIntent] + method. + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.output_audio_config]. + 2. If + [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio.config][google.cloud.dialogflow.cx.v3beta1.AudioInput.config], + all subsequent messages must contain + [query_input.audio.audio][google.cloud.dialogflow.cx.v3beta1.AudioInput.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.cx.v3beta1.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.dialogflowcx_v3beta1.types.StreamingDetectIntentResponse]: + The top-level message returned from the + StreamingDetectIntent method. + + Multiple response messages can be returned in order: + + 1. If the input was set to streaming audio, the first + one or more messages contain recognition_result. + Each recognition_result represents a more complete + transcript of what the user said. The last + recognition_result has is_final set to true. + 2. If enable_partial_response is true, the following + N messages (currently 1 <= N <= 4) contain + detect_intent_response. The first (N-1) + detect_intent_responses will have response_type + set to PARTIAL. The last detect_intent_response + has response_type set to FINAL. If response_type + is false, response stream only contains the final + detect_intent_response. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.streaming_detect_intent, + default_timeout=220.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def match_intent(self, + request: session.MatchIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.MatchIntentResponse: + r"""Returns preliminary intent match results, doesn't + change the session status. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest`): + The request object. Request of [MatchIntent][]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.MatchIntentResponse: + Response of [MatchIntent][]. + """ + # Create or coerce a protobuf request object. + request = session.MatchIntentRequest(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.match_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(( + ("session", request.session), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def fulfill_intent(self, + request: session.FulfillIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.FulfillIntentResponse: + r"""Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3beta1.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.FulfillIntentRequest`): + The request object. Request of [FulfillIntent][] + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.FulfillIntentResponse: + Response of [FulfillIntent][] + """ + # Create or coerce a protobuf request object. + request = session.FulfillIntentRequest(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.fulfill_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(( + ("match_intent_request.session", request.match_intent_request.session), + )), + ) + + # 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionsAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py new file mode 100644 index 00000000..197afabe --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/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 +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.dialogflowcx_v3beta1.types import audio_config +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import session +from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SessionsGrpcTransport +from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport + + +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 session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.DetectIntent] + method to determine user intent and respond. + """ + + @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 entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_path(project: str,location: str,agent: str,session: str,) -> str: + """Returns a fully-qualified session string.""" + return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format(project=project, location=location, agent=agent, session=session, ) + + @staticmethod + def parse_session_path(path: str) -> Dict[str,str]: + """Parses a session path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def session_entity_type_path(project: str,location: str,agent: str,session: str,entity_type: str,) -> str: + """Returns a fully-qualified session_entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, 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.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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: session.DetectIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> 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 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.dialogflowcx_v3beta1.types.DetectIntentRequest): + The request object. The request to detect user's intent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.DetectIntentResponse: + The message returned from the + DetectIntent method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a session.DetectIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session.DetectIntentRequest): + request = session.DetectIntentRequest(request) + + # 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.dialogflowcx_v3beta1.types.StreamingDetectIntentRequest]): + The request object iterator. The top-level message sent by the + client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.StreamingDetectIntent] + method. + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it + should also contain + [output_audio_config][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.output_audio_config]. + 2. If + [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio.config][google.cloud.dialogflow.cx.v3beta1.AudioInput.config], + all subsequent messages must contain + [query_input.audio.audio][google.cloud.dialogflow.cx.v3beta1.AudioInput.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.cx.v3beta1.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.dialogflowcx_v3beta1.types.StreamingDetectIntentResponse]: + The top-level message returned from the + StreamingDetectIntent method. + + Multiple response messages can be returned in order: + + 1. If the input was set to streaming audio, the first + one or more messages contain recognition_result. + Each recognition_result represents a more complete + transcript of what the user said. The last + recognition_result has is_final set to true. + 2. If enable_partial_response is true, the following + N messages (currently 1 <= N <= 4) contain + detect_intent_response. The first (N-1) + detect_intent_responses will have response_type + set to PARTIAL. The last detect_intent_response + has response_type set to FINAL. If response_type + is false, response stream only contains the final + detect_intent_response. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.streaming_detect_intent] + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def match_intent(self, + request: session.MatchIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.MatchIntentResponse: + r"""Returns preliminary intent match results, doesn't + change the session status. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest): + The request object. Request of [MatchIntent][]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.MatchIntentResponse: + Response of [MatchIntent][]. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a session.MatchIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session.MatchIntentRequest): + request = session.MatchIntentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.match_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 fulfill_intent(self, + request: session.FulfillIntentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> session.FulfillIntentResponse: + r"""Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3beta1.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.FulfillIntentRequest): + The request object. Request of [FulfillIntent][] + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.FulfillIntentResponse: + Response of [FulfillIntent][] + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a session.FulfillIntentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, session.FulfillIntentRequest): + request = session.FulfillIntentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fulfill_intent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("match_intent_request.session", request.match_intent_request.session), + )), + ) + + # 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SessionsClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py new file mode 100644 index 00000000..fde19f61 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py new file mode 100644 index 00000000..14df3697 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import session + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +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, + ), + self.match_intent: gapic_v1.method.wrap_method( + self.match_intent, + default_timeout=None, + client_info=client_info, + ), + self.fulfill_intent: gapic_v1.method.wrap_method( + self.fulfill_intent, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def detect_intent(self) -> Callable[ + [session.DetectIntentRequest], + Union[ + session.DetectIntentResponse, + Awaitable[session.DetectIntentResponse] + ]]: + raise NotImplementedError() + + @property + def streaming_detect_intent(self) -> Callable[ + [session.StreamingDetectIntentRequest], + Union[ + session.StreamingDetectIntentResponse, + Awaitable[session.StreamingDetectIntentResponse] + ]]: + raise NotImplementedError() + + @property + def match_intent(self) -> Callable[ + [session.MatchIntentRequest], + Union[ + session.MatchIntentResponse, + Awaitable[session.MatchIntentResponse] + ]]: + raise NotImplementedError() + + @property + def fulfill_intent(self) -> Callable[ + [session.FulfillIntentRequest], + Union[ + session.FulfillIntentResponse, + Awaitable[session.FulfillIntentResponse] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SessionsTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py new file mode 100644 index 00000000..43f88d66 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.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 warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import session +from .base import SessionsTransport, DEFAULT_CLIENT_INFO + + +class SessionsGrpcTransport(SessionsTransport): + """gRPC backend transport for Sessions. + + A session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.DetectIntent] + method to determine user intent and respond. + + 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[ + [session.DetectIntentRequest], + 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 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.cx.v3beta1.Sessions/DetectIntent', + request_serializer=session.DetectIntentRequest.serialize, + response_deserializer=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.cx.v3beta1.Sessions/StreamingDetectIntent', + request_serializer=session.StreamingDetectIntentRequest.serialize, + response_deserializer=session.StreamingDetectIntentResponse.deserialize, + ) + return self._stubs['streaming_detect_intent'] + + @property + def match_intent(self) -> Callable[ + [session.MatchIntentRequest], + session.MatchIntentResponse]: + r"""Return a callable for the match intent method over gRPC. + + Returns preliminary intent match results, doesn't + change the session status. + + Returns: + Callable[[~.MatchIntentRequest], + ~.MatchIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'match_intent' not in self._stubs: + self._stubs['match_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Sessions/MatchIntent', + request_serializer=session.MatchIntentRequest.serialize, + response_deserializer=session.MatchIntentResponse.deserialize, + ) + return self._stubs['match_intent'] + + @property + def fulfill_intent(self) -> Callable[ + [session.FulfillIntentRequest], + session.FulfillIntentResponse]: + r"""Return a callable for the fulfill intent method over gRPC. + + Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3beta1.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Returns: + Callable[[~.FulfillIntentRequest], + ~.FulfillIntentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fulfill_intent' not in self._stubs: + self._stubs['fulfill_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Sessions/FulfillIntent', + request_serializer=session.FulfillIntentRequest.serialize, + response_deserializer=session.FulfillIntentResponse.deserialize, + ) + return self._stubs['fulfill_intent'] + + +__all__ = ( + 'SessionsGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py new file mode 100644 index 00000000..9e0d3c1a --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py @@ -0,0 +1,354 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import session +from .base import SessionsTransport, DEFAULT_CLIENT_INFO +from .grpc import SessionsGrpcTransport + + +class SessionsGrpcAsyncIOTransport(SessionsTransport): + """gRPC AsyncIO backend transport for Sessions. + + A session represents an interaction with a user. You retrieve user + input and pass it to the + [DetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.DetectIntent] + method to determine user intent and respond. + + 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[ + [session.DetectIntentRequest], + Awaitable[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 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.cx.v3beta1.Sessions/DetectIntent', + request_serializer=session.DetectIntentRequest.serialize, + response_deserializer=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.cx.v3beta1.Sessions/StreamingDetectIntent', + request_serializer=session.StreamingDetectIntentRequest.serialize, + response_deserializer=session.StreamingDetectIntentResponse.deserialize, + ) + return self._stubs['streaming_detect_intent'] + + @property + def match_intent(self) -> Callable[ + [session.MatchIntentRequest], + Awaitable[session.MatchIntentResponse]]: + r"""Return a callable for the match intent method over gRPC. + + Returns preliminary intent match results, doesn't + change the session status. + + Returns: + Callable[[~.MatchIntentRequest], + Awaitable[~.MatchIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'match_intent' not in self._stubs: + self._stubs['match_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Sessions/MatchIntent', + request_serializer=session.MatchIntentRequest.serialize, + response_deserializer=session.MatchIntentResponse.deserialize, + ) + return self._stubs['match_intent'] + + @property + def fulfill_intent(self) -> Callable[ + [session.FulfillIntentRequest], + Awaitable[session.FulfillIntentResponse]]: + r"""Return a callable for the fulfill intent method over gRPC. + + Fulfills a matched intent returned by + [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent]. + Must be called after + [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent], + with input from + [MatchIntentResponse][google.cloud.dialogflow.cx.v3beta1.MatchIntentResponse]. + Otherwise, the behavior is undefined. + + Returns: + Callable[[~.FulfillIntentRequest], + Awaitable[~.FulfillIntentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fulfill_intent' not in self._stubs: + self._stubs['fulfill_intent'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Sessions/FulfillIntent', + request_serializer=session.FulfillIntentRequest.serialize, + response_deserializer=session.FulfillIntentResponse.deserialize, + ) + return self._stubs['fulfill_intent'] + + +__all__ = ( + 'SessionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py new file mode 100644 index 00000000..938c210f --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/__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 TestCasesClient +from .async_client import TestCasesAsyncClient + +__all__ = ( + 'TestCasesClient', + 'TestCasesAsyncClient', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py new file mode 100644 index 00000000..4f110481 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py @@ -0,0 +1,1073 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.test_cases import pagers +from google.cloud.dialogflowcx_v3beta1.types import test_case +from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport +from .client import TestCasesClient + + +class TestCasesAsyncClient: + """Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult]. + """ + + _client: TestCasesClient + + DEFAULT_ENDPOINT = TestCasesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TestCasesClient.DEFAULT_MTLS_ENDPOINT + + agent_path = staticmethod(TestCasesClient.agent_path) + parse_agent_path = staticmethod(TestCasesClient.parse_agent_path) + entity_type_path = staticmethod(TestCasesClient.entity_type_path) + parse_entity_type_path = staticmethod(TestCasesClient.parse_entity_type_path) + environment_path = staticmethod(TestCasesClient.environment_path) + parse_environment_path = staticmethod(TestCasesClient.parse_environment_path) + flow_path = staticmethod(TestCasesClient.flow_path) + parse_flow_path = staticmethod(TestCasesClient.parse_flow_path) + intent_path = staticmethod(TestCasesClient.intent_path) + parse_intent_path = staticmethod(TestCasesClient.parse_intent_path) + page_path = staticmethod(TestCasesClient.page_path) + parse_page_path = staticmethod(TestCasesClient.parse_page_path) + test_case_path = staticmethod(TestCasesClient.test_case_path) + parse_test_case_path = staticmethod(TestCasesClient.parse_test_case_path) + test_case_result_path = staticmethod(TestCasesClient.test_case_result_path) + parse_test_case_result_path = staticmethod(TestCasesClient.parse_test_case_result_path) + transition_route_group_path = staticmethod(TestCasesClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(TestCasesClient.parse_transition_route_group_path) + webhook_path = staticmethod(TestCasesClient.webhook_path) + parse_webhook_path = staticmethod(TestCasesClient.parse_webhook_path) + common_billing_account_path = staticmethod(TestCasesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TestCasesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TestCasesClient.common_folder_path) + parse_common_folder_path = staticmethod(TestCasesClient.parse_common_folder_path) + common_organization_path = staticmethod(TestCasesClient.common_organization_path) + parse_common_organization_path = staticmethod(TestCasesClient.parse_common_organization_path) + common_project_path = staticmethod(TestCasesClient.common_project_path) + parse_common_project_path = staticmethod(TestCasesClient.parse_common_project_path) + common_location_path = staticmethod(TestCasesClient.common_location_path) + parse_common_location_path = staticmethod(TestCasesClient.parse_common_location_path) + + @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: + TestCasesAsyncClient: The constructed client. + """ + return TestCasesClient.from_service_account_info.__func__(TestCasesAsyncClient, 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: + TestCasesAsyncClient: The constructed client. + """ + return TestCasesClient.from_service_account_file.__func__(TestCasesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> TestCasesTransport: + """Returns the transport used by the client instance. + + Returns: + TestCasesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(TestCasesClient).get_transport_class, type(TestCasesClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, TestCasesTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the test cases 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, ~.TestCasesTransport]): 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 = TestCasesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_test_cases(self, + request: test_case.ListTestCasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCasesAsyncPager: + r"""Fetches a list of test cases for a given agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest`): + The request object. The request message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. + parent (:class:`str`): + Required. The agent to list all pages for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers.ListTestCasesAsyncPager: + The response message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. + + 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 = test_case.ListTestCasesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListTestCasesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_delete_test_cases(self, + request: test_case.BatchDeleteTestCasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Batch deletes test cases. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.BatchDeleteTestCasesRequest`): + The request object. The request message for + [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchDeleteTestCases]. + parent (:class:`str`): + Required. The agent to delete test cases from. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = test_case.BatchDeleteTestCasesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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 get_test_case(self, + request: test_case.GetTestCaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCase: + r"""Gets a test case. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetTestCaseRequest`): + The request object. The request message for + [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCase]. + name (:class:`str`): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = test_case.GetTestCaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_test_case(self, + request: gcdc_test_case.CreateTestCaseRequest = None, + *, + parent: str = None, + test_case: gcdc_test_case.TestCase = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Creates a test case for the given agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateTestCaseRequest`): + The request object. The request message for + [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.CreateTestCase]. + parent (:class:`str`): + Required. The agent to create the test case for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_case (:class:`google.cloud.dialogflowcx_v3beta1.types.TestCase`): + Required. The test case to create. + This corresponds to the ``test_case`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, test_case]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_test_case.CreateTestCaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if test_case is not None: + request.test_case = test_case + + # 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_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_test_case(self, + request: gcdc_test_case.UpdateTestCaseRequest = None, + *, + test_case: gcdc_test_case.TestCase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Updates the specified test case. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateTestCaseRequest`): + The request object. The request message for + [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.UpdateTestCase]. + test_case (:class:`google.cloud.dialogflowcx_v3beta1.types.TestCase`): + Required. The test case to update. + This corresponds to the ``test_case`` 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 should be + updated. The + [``creationTime``][google.cloud.dialogflow.cx.v3beta1.TestCase.creation_time] + and + [``lastTestResult``][google.cloud.dialogflow.cx.v3beta1.TestCase.last_test_result] + cannot 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.dialogflowcx_v3beta1.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([test_case, 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 = gcdc_test_case.UpdateTestCaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if test_case is not None: + request.test_case = test_case + if update_mask is not None: + 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_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("test_case.name", request.test_case.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_test_case(self, + request: test_case.RunTestCaseRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off a test case run. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.RunTestCaseRequest`): + The request object. The request message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.RunTestCaseResponse` + The response message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. + + """ + # Create or coerce a protobuf request object. + request = test_case.RunTestCaseRequest(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.run_test_case, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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, + test_case.RunTestCaseResponse, + metadata_type=test_case.RunTestCaseMetadata, + ) + + # Done; return the response. + return response + + async def batch_run_test_cases(self, + request: test_case.BatchRunTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off a batch run of test cases. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesRequest`): + The request object. The request message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesResponse` + The response message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. + + """ + # Create or coerce a protobuf request object. + request = test_case.BatchRunTestCasesRequest(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_run_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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, + test_case.BatchRunTestCasesResponse, + metadata_type=test_case.BatchRunTestCasesMetadata, + ) + + # Done; return the response. + return response + + async def calculate_coverage(self, + request: test_case.CalculateCoverageRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.CalculateCoverageResponse: + r"""Calculates the test coverage for an agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageRequest`): + The request object. The request message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageResponse: + The response message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. + + """ + # Create or coerce a protobuf request object. + request = test_case.CalculateCoverageRequest(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.calculate_coverage, + default_timeout=None, + client_info=DEFAULT_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", request.agent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_test_cases(self, + request: test_case.ImportTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the test cases from a Cloud Storage bucket or + a local file. It always creates new test cases and won't + overwite any existing ones. The provided ID in the + imported test case is neglected. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesRequest`): + The request object. The request message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesResponse` + The response message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. + + """ + # Create or coerce a protobuf request object. + request = test_case.ImportTestCasesRequest(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_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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, + test_case.ImportTestCasesResponse, + metadata_type=test_case.ImportTestCasesMetadata, + ) + + # Done; return the response. + return response + + async def export_test_cases(self, + request: test_case.ExportTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the test cases under the agent to a Cloud + Storage bucket or a local file. Filter can be applied to + export a subset of test cases. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest`): + The request object. The request message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesResponse` + The response message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. + + """ + # Create or coerce a protobuf request object. + request = test_case.ExportTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_test_cases, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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, + test_case.ExportTestCasesResponse, + metadata_type=test_case.ExportTestCasesMetadata, + ) + + # Done; return the response. + return response + + async def list_test_case_results(self, + request: test_case.ListTestCaseResultsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCaseResultsAsyncPager: + r"""Fetches a list of results for a given test case. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsRequest`): + The request object. The request message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. + parent (:class:`str`): + Required. The test case to list results for. Format: + ``projects//locations//agents// testCases/``. + Specify a ``-`` as a wildcard for TestCase ID to list + results across multiple test cases. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers.ListTestCaseResultsAsyncPager: + The response message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. + + 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 = test_case.ListTestCaseResultsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_test_case_results, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListTestCaseResultsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_test_case_result(self, + request: test_case.GetTestCaseResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCaseResult: + r"""Gets a test case result. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetTestCaseResultRequest`): + The request object. The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCaseResult]. + name (:class:`str`): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.TestCaseResult: + Represents a result from running a + test case in an agent environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = test_case.GetTestCaseResultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_test_case_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TestCasesAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py new file mode 100644 index 00000000..f42b5eb8 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py @@ -0,0 +1,1346 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.test_cases import pagers +from google.cloud.dialogflowcx_v3beta1.types import test_case +from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TestCasesGrpcTransport +from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport + + +class TestCasesClientMeta(type): + """Metaclass for the TestCases 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[TestCasesTransport]] + _transport_registry["grpc"] = TestCasesGrpcTransport + _transport_registry["grpc_asyncio"] = TestCasesGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[TestCasesTransport]: + """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 TestCasesClient(metaclass=TestCasesClientMeta): + """Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult]. + """ + + @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: + TestCasesClient: 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: + TestCasesClient: 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) -> TestCasesTransport: + """Returns the transport used by the client instance. + + Returns: + TestCasesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path(project: str,location: str,agent: str,) -> str: + """Returns a fully-qualified agent string.""" + return "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str,str]: + """Parses a agent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: + """Returns a fully-qualified entity_type string.""" + return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + + @staticmethod + def parse_entity_type_path(path: str) -> Dict[str,str]: + """Parses a entity_type path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def environment_path(project: str,location: str,agent: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def test_case_path(project: str,location: str,agent: str,test_case: str,) -> str: + """Returns a fully-qualified test_case string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(project=project, location=location, agent=agent, test_case=test_case, ) + + @staticmethod + def parse_test_case_path(path: str) -> Dict[str,str]: + """Parses a test_case path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def test_case_result_path(project: str,location: str,agent: str,test_case: str,result: str,) -> str: + """Returns a fully-qualified test_case_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) + + @staticmethod + def parse_test_case_result_path(path: str) -> Dict[str,str]: + """Parses a test_case_result path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, TestCasesTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the test cases 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, TestCasesTransport]): 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, TestCasesTransport): + # transport is a TestCasesTransport 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_test_cases(self, + request: test_case.ListTestCasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCasesPager: + r"""Fetches a list of test cases for a given agent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest): + The request object. The request message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. + parent (str): + Required. The agent to list all pages for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers.ListTestCasesPager: + The response message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. + + 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 test_case.ListTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ListTestCasesRequest): + request = test_case.ListTestCasesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListTestCasesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_delete_test_cases(self, + request: test_case.BatchDeleteTestCasesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Batch deletes test cases. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.BatchDeleteTestCasesRequest): + The request object. The request message for + [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchDeleteTestCases]. + parent (str): + Required. The agent to delete test cases from. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 test_case.BatchDeleteTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.BatchDeleteTestCasesRequest): + request = test_case.BatchDeleteTestCasesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_test_cases] + + # Certain fields should be 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 get_test_case(self, + request: test_case.GetTestCaseRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCase: + r"""Gets a test case. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetTestCaseRequest): + The request object. The request message for + [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCase]. + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a test_case.GetTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.GetTestCaseRequest): + request = test_case.GetTestCaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_test_case] + + # Certain fields should be provided 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_test_case(self, + request: gcdc_test_case.CreateTestCaseRequest = None, + *, + parent: str = None, + test_case: gcdc_test_case.TestCase = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Creates a test case for the given agent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateTestCaseRequest): + The request object. The request message for + [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.CreateTestCase]. + parent (str): + Required. The agent to create the test case for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): + Required. The test case to create. + This corresponds to the ``test_case`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, test_case]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_test_case.CreateTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_test_case.CreateTestCaseRequest): + request = gcdc_test_case.CreateTestCaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if test_case is not None: + request.test_case = test_case + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_test_case] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_test_case(self, + request: gcdc_test_case.UpdateTestCaseRequest = None, + *, + test_case: gcdc_test_case.TestCase = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_test_case.TestCase: + r"""Updates the specified test case. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateTestCaseRequest): + The request object. The request message for + [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.UpdateTestCase]. + test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): + Required. The test case to update. + This corresponds to the ``test_case`` 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 should be + updated. The + [``creationTime``][google.cloud.dialogflow.cx.v3beta1.TestCase.creation_time] + and + [``lastTestResult``][google.cloud.dialogflow.cx.v3beta1.TestCase.last_test_result] + cannot 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.dialogflowcx_v3beta1.types.TestCase: + Represents a test case. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([test_case, 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 gcdc_test_case.UpdateTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_test_case.UpdateTestCaseRequest): + request = gcdc_test_case.UpdateTestCaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if test_case is not None: + request.test_case = test_case + if update_mask is not None: + 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_test_case] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("test_case.name", request.test_case.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_test_case(self, + request: test_case.RunTestCaseRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Kicks off a test case run. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.RunTestCaseRequest): + The request object. The request message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.RunTestCaseResponse` + The response message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.RunTestCaseRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.RunTestCaseRequest): + request = test_case.RunTestCaseRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_test_case] + + # Certain fields should be provided 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, + test_case.RunTestCaseResponse, + metadata_type=test_case.RunTestCaseMetadata, + ) + + # Done; return the response. + return response + + def batch_run_test_cases(self, + request: test_case.BatchRunTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Kicks off a batch run of test cases. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesRequest): + The request object. The request message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesResponse` + The response message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.BatchRunTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.BatchRunTestCasesRequest): + request = test_case.BatchRunTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_run_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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, + test_case.BatchRunTestCasesResponse, + metadata_type=test_case.BatchRunTestCasesMetadata, + ) + + # Done; return the response. + return response + + def calculate_coverage(self, + request: test_case.CalculateCoverageRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.CalculateCoverageResponse: + r"""Calculates the test coverage for an agent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageRequest): + The request object. The request message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageResponse: + The response message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.CalculateCoverageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.CalculateCoverageRequest): + request = test_case.CalculateCoverageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.calculate_coverage] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("agent", request.agent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_test_cases(self, + request: test_case.ImportTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports the test cases from a Cloud Storage bucket or + a local file. It always creates new test cases and won't + overwite any existing ones. The provided ID in the + imported test case is neglected. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesRequest): + The request object. The request message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesResponse` + The response message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.ImportTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ImportTestCasesRequest): + request = test_case.ImportTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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, + test_case.ImportTestCasesResponse, + metadata_type=test_case.ImportTestCasesMetadata, + ) + + # Done; return the response. + return response + + def export_test_cases(self, + request: test_case.ExportTestCasesRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the test cases under the agent to a Cloud + Storage bucket or a local file. Filter can be applied to + export a subset of test cases. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest): + The request object. The request message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesResponse` + The response message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a test_case.ExportTestCasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ExportTestCasesRequest): + request = test_case.ExportTestCasesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_test_cases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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, + test_case.ExportTestCasesResponse, + metadata_type=test_case.ExportTestCasesMetadata, + ) + + # Done; return the response. + return response + + def list_test_case_results(self, + request: test_case.ListTestCaseResultsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTestCaseResultsPager: + r"""Fetches a list of results for a given test case. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsRequest): + The request object. The request message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. + parent (str): + Required. The test case to list results for. Format: + ``projects//locations//agents// testCases/``. + Specify a ``-`` as a wildcard for TestCase ID to list + results across multiple test cases. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers.ListTestCaseResultsPager: + The response message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. + + 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 test_case.ListTestCaseResultsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.ListTestCaseResultsRequest): + request = test_case.ListTestCaseResultsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_test_case_results] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListTestCaseResultsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_test_case_result(self, + request: test_case.GetTestCaseResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCaseResult: + r"""Gets a test case result. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetTestCaseResultRequest): + The request object. The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCaseResult]. + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.TestCaseResult: + Represents a result from running a + test case in an agent environment. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a test_case.GetTestCaseResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.GetTestCaseResultRequest): + request = test_case.GetTestCaseResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_test_case_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TestCasesClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py new file mode 100644 index 00000000..1d7f479e --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/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.dialogflowcx_v3beta1.types import test_case + + +class ListTestCasesPager: + """A pager for iterating through ``list_test_cases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``test_cases`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTestCases`` requests and continue to iterate + through the ``test_cases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse` + 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[..., test_case.ListTestCasesResponse], + request: test_case.ListTestCasesRequest, + response: test_case.ListTestCasesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse): + 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 = test_case.ListTestCasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[test_case.ListTestCasesResponse]: + 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[test_case.TestCase]: + for page in self.pages: + yield from page.test_cases + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTestCasesAsyncPager: + """A pager for iterating through ``list_test_cases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``test_cases`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTestCases`` requests and continue to iterate + through the ``test_cases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse` + 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[test_case.ListTestCasesResponse]], + request: test_case.ListTestCasesRequest, + response: test_case.ListTestCasesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse): + 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 = test_case.ListTestCasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[test_case.ListTestCasesResponse]: + 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[test_case.TestCase]: + async def async_generator(): + async for page in self.pages: + for response in page.test_cases: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTestCaseResultsPager: + """A pager for iterating through ``list_test_case_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``test_case_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTestCaseResults`` requests and continue to iterate + through the ``test_case_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse` + 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[..., test_case.ListTestCaseResultsResponse], + request: test_case.ListTestCaseResultsRequest, + response: test_case.ListTestCaseResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse): + 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 = test_case.ListTestCaseResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[test_case.ListTestCaseResultsResponse]: + 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[test_case.TestCaseResult]: + for page in self.pages: + yield from page.test_case_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTestCaseResultsAsyncPager: + """A pager for iterating through ``list_test_case_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``test_case_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTestCaseResults`` requests and continue to iterate + through the ``test_case_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse` + 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[test_case.ListTestCaseResultsResponse]], + request: test_case.ListTestCaseResultsRequest, + response: test_case.ListTestCaseResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse): + 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 = test_case.ListTestCaseResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[test_case.ListTestCaseResultsResponse]: + 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[test_case.TestCaseResult]: + async def async_generator(): + async for page in self.pages: + for response in page.test_case_results: + 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py new file mode 100644 index 00000000..52d2730d --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/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 TestCasesTransport +from .grpc import TestCasesGrpcTransport +from .grpc_asyncio import TestCasesGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TestCasesTransport]] +_transport_registry['grpc'] = TestCasesGrpcTransport +_transport_registry['grpc_asyncio'] = TestCasesGrpcAsyncIOTransport + +__all__ = ( + 'TestCasesTransport', + 'TestCasesGrpcTransport', + 'TestCasesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py new file mode 100644 index 00000000..d6644a12 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py @@ -0,0 +1,346 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.dialogflowcx_v3beta1.types import test_case +from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 # 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-dialogflowcx', + ).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 TestCasesTransport(abc.ABC): + """Abstract transport class for TestCases.""" + + 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_test_cases: gapic_v1.method.wrap_method( + self.list_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_test_cases: gapic_v1.method.wrap_method( + self.batch_delete_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.get_test_case: gapic_v1.method.wrap_method( + self.get_test_case, + default_timeout=None, + client_info=client_info, + ), + self.create_test_case: gapic_v1.method.wrap_method( + self.create_test_case, + default_timeout=None, + client_info=client_info, + ), + self.update_test_case: gapic_v1.method.wrap_method( + self.update_test_case, + default_timeout=None, + client_info=client_info, + ), + self.run_test_case: gapic_v1.method.wrap_method( + self.run_test_case, + default_timeout=None, + client_info=client_info, + ), + self.batch_run_test_cases: gapic_v1.method.wrap_method( + self.batch_run_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.calculate_coverage: gapic_v1.method.wrap_method( + self.calculate_coverage, + default_timeout=None, + client_info=client_info, + ), + self.import_test_cases: gapic_v1.method.wrap_method( + self.import_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.export_test_cases: gapic_v1.method.wrap_method( + self.export_test_cases, + default_timeout=None, + client_info=client_info, + ), + self.list_test_case_results: gapic_v1.method.wrap_method( + self.list_test_case_results, + default_timeout=None, + client_info=client_info, + ), + self.get_test_case_result: gapic_v1.method.wrap_method( + self.get_test_case_result, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_test_cases(self) -> Callable[ + [test_case.ListTestCasesRequest], + Union[ + test_case.ListTestCasesResponse, + Awaitable[test_case.ListTestCasesResponse] + ]]: + raise NotImplementedError() + + @property + def batch_delete_test_cases(self) -> Callable[ + [test_case.BatchDeleteTestCasesRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_test_case(self) -> Callable[ + [test_case.GetTestCaseRequest], + Union[ + test_case.TestCase, + Awaitable[test_case.TestCase] + ]]: + raise NotImplementedError() + + @property + def create_test_case(self) -> Callable[ + [gcdc_test_case.CreateTestCaseRequest], + Union[ + gcdc_test_case.TestCase, + Awaitable[gcdc_test_case.TestCase] + ]]: + raise NotImplementedError() + + @property + def update_test_case(self) -> Callable[ + [gcdc_test_case.UpdateTestCaseRequest], + Union[ + gcdc_test_case.TestCase, + Awaitable[gcdc_test_case.TestCase] + ]]: + raise NotImplementedError() + + @property + def run_test_case(self) -> Callable[ + [test_case.RunTestCaseRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def batch_run_test_cases(self) -> Callable[ + [test_case.BatchRunTestCasesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def calculate_coverage(self) -> Callable[ + [test_case.CalculateCoverageRequest], + Union[ + test_case.CalculateCoverageResponse, + Awaitable[test_case.CalculateCoverageResponse] + ]]: + raise NotImplementedError() + + @property + def import_test_cases(self) -> Callable[ + [test_case.ImportTestCasesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_test_cases(self) -> Callable[ + [test_case.ExportTestCasesRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_test_case_results(self) -> Callable[ + [test_case.ListTestCaseResultsRequest], + Union[ + test_case.ListTestCaseResultsResponse, + Awaitable[test_case.ListTestCaseResultsResponse] + ]]: + raise NotImplementedError() + + @property + def get_test_case_result(self) -> Callable[ + [test_case.GetTestCaseResultRequest], + Union[ + test_case.TestCaseResult, + Awaitable[test_case.TestCaseResult] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'TestCasesTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py new file mode 100644 index 00000000..97c6b359 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py @@ -0,0 +1,562 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import test_case +from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import TestCasesTransport, DEFAULT_CLIENT_INFO + + +class TestCasesGrpcTransport(TestCasesTransport): + """gRPC backend transport for TestCases. + + Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult]. + + 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_test_cases(self) -> Callable[ + [test_case.ListTestCasesRequest], + test_case.ListTestCasesResponse]: + r"""Return a callable for the list test cases method over gRPC. + + Fetches a list of test cases for a given agent. + + Returns: + Callable[[~.ListTestCasesRequest], + ~.ListTestCasesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_cases' not in self._stubs: + self._stubs['list_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/ListTestCases', + request_serializer=test_case.ListTestCasesRequest.serialize, + response_deserializer=test_case.ListTestCasesResponse.deserialize, + ) + return self._stubs['list_test_cases'] + + @property + def batch_delete_test_cases(self) -> Callable[ + [test_case.BatchDeleteTestCasesRequest], + empty_pb2.Empty]: + r"""Return a callable for the batch delete test cases method over gRPC. + + Batch deletes test cases. + + Returns: + Callable[[~.BatchDeleteTestCasesRequest], + ~.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 'batch_delete_test_cases' not in self._stubs: + self._stubs['batch_delete_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchDeleteTestCases', + request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['batch_delete_test_cases'] + + @property + def get_test_case(self) -> Callable[ + [test_case.GetTestCaseRequest], + test_case.TestCase]: + r"""Return a callable for the get test case method over gRPC. + + Gets a test case. + + Returns: + Callable[[~.GetTestCaseRequest], + ~.TestCase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case' not in self._stubs: + self._stubs['get_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCase', + request_serializer=test_case.GetTestCaseRequest.serialize, + response_deserializer=test_case.TestCase.deserialize, + ) + return self._stubs['get_test_case'] + + @property + def create_test_case(self) -> Callable[ + [gcdc_test_case.CreateTestCaseRequest], + gcdc_test_case.TestCase]: + r"""Return a callable for the create test case method over gRPC. + + Creates a test case for the given agent. + + Returns: + Callable[[~.CreateTestCaseRequest], + ~.TestCase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_test_case' not in self._stubs: + self._stubs['create_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/CreateTestCase', + request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['create_test_case'] + + @property + def update_test_case(self) -> Callable[ + [gcdc_test_case.UpdateTestCaseRequest], + gcdc_test_case.TestCase]: + r"""Return a callable for the update test case method over gRPC. + + Updates the specified test case. + + Returns: + Callable[[~.UpdateTestCaseRequest], + ~.TestCase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_test_case' not in self._stubs: + self._stubs['update_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/UpdateTestCase', + request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['update_test_case'] + + @property + def run_test_case(self) -> Callable[ + [test_case.RunTestCaseRequest], + operations_pb2.Operation]: + r"""Return a callable for the run test case method over gRPC. + + Kicks off a test case run. + + Returns: + Callable[[~.RunTestCaseRequest], + ~.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 'run_test_case' not in self._stubs: + self._stubs['run_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/RunTestCase', + request_serializer=test_case.RunTestCaseRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_test_case'] + + @property + def batch_run_test_cases(self) -> Callable[ + [test_case.BatchRunTestCasesRequest], + operations_pb2.Operation]: + r"""Return a callable for the batch run test cases method over gRPC. + + Kicks off a batch run of test cases. + + Returns: + Callable[[~.BatchRunTestCasesRequest], + ~.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_run_test_cases' not in self._stubs: + self._stubs['batch_run_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchRunTestCases', + request_serializer=test_case.BatchRunTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_run_test_cases'] + + @property + def calculate_coverage(self) -> Callable[ + [test_case.CalculateCoverageRequest], + test_case.CalculateCoverageResponse]: + r"""Return a callable for the calculate coverage method over gRPC. + + Calculates the test coverage for an agent. + + Returns: + Callable[[~.CalculateCoverageRequest], + ~.CalculateCoverageResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'calculate_coverage' not in self._stubs: + self._stubs['calculate_coverage'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/CalculateCoverage', + request_serializer=test_case.CalculateCoverageRequest.serialize, + response_deserializer=test_case.CalculateCoverageResponse.deserialize, + ) + return self._stubs['calculate_coverage'] + + @property + def import_test_cases(self) -> Callable[ + [test_case.ImportTestCasesRequest], + operations_pb2.Operation]: + r"""Return a callable for the import test cases method over gRPC. + + Imports the test cases from a Cloud Storage bucket or + a local file. It always creates new test cases and won't + overwite any existing ones. The provided ID in the + imported test case is neglected. + + Returns: + Callable[[~.ImportTestCasesRequest], + ~.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_test_cases' not in self._stubs: + self._stubs['import_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/ImportTestCases', + request_serializer=test_case.ImportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_test_cases'] + + @property + def export_test_cases(self) -> Callable[ + [test_case.ExportTestCasesRequest], + operations_pb2.Operation]: + r"""Return a callable for the export test cases method over gRPC. + + Exports the test cases under the agent to a Cloud + Storage bucket or a local file. Filter can be applied to + export a subset of test cases. + + Returns: + Callable[[~.ExportTestCasesRequest], + ~.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_test_cases' not in self._stubs: + self._stubs['export_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/ExportTestCases', + request_serializer=test_case.ExportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_test_cases'] + + @property + def list_test_case_results(self) -> Callable[ + [test_case.ListTestCaseResultsRequest], + test_case.ListTestCaseResultsResponse]: + r"""Return a callable for the list test case results method over gRPC. + + Fetches a list of results for a given test case. + + Returns: + Callable[[~.ListTestCaseResultsRequest], + ~.ListTestCaseResultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_case_results' not in self._stubs: + self._stubs['list_test_case_results'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/ListTestCaseResults', + request_serializer=test_case.ListTestCaseResultsRequest.serialize, + response_deserializer=test_case.ListTestCaseResultsResponse.deserialize, + ) + return self._stubs['list_test_case_results'] + + @property + def get_test_case_result(self) -> Callable[ + [test_case.GetTestCaseResultRequest], + test_case.TestCaseResult]: + r"""Return a callable for the get test case result method over gRPC. + + Gets a test case result. + + Returns: + Callable[[~.GetTestCaseResultRequest], + ~.TestCaseResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case_result' not in self._stubs: + self._stubs['get_test_case_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCaseResult', + request_serializer=test_case.GetTestCaseResultRequest.serialize, + response_deserializer=test_case.TestCaseResult.deserialize, + ) + return self._stubs['get_test_case_result'] + + +__all__ = ( + 'TestCasesGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py new file mode 100644 index 00000000..3323ca19 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py @@ -0,0 +1,566 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import test_case +from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import TestCasesTransport, DEFAULT_CLIENT_INFO +from .grpc import TestCasesGrpcTransport + + +class TestCasesGrpcAsyncIOTransport(TestCasesTransport): + """gRPC AsyncIO backend transport for TestCases. + + Service for managing [Test + Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and [Test Case + Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult]. + + 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_test_cases(self) -> Callable[ + [test_case.ListTestCasesRequest], + Awaitable[test_case.ListTestCasesResponse]]: + r"""Return a callable for the list test cases method over gRPC. + + Fetches a list of test cases for a given agent. + + Returns: + Callable[[~.ListTestCasesRequest], + Awaitable[~.ListTestCasesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_cases' not in self._stubs: + self._stubs['list_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/ListTestCases', + request_serializer=test_case.ListTestCasesRequest.serialize, + response_deserializer=test_case.ListTestCasesResponse.deserialize, + ) + return self._stubs['list_test_cases'] + + @property + def batch_delete_test_cases(self) -> Callable[ + [test_case.BatchDeleteTestCasesRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the batch delete test cases method over gRPC. + + Batch deletes test cases. + + Returns: + Callable[[~.BatchDeleteTestCasesRequest], + 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 'batch_delete_test_cases' not in self._stubs: + self._stubs['batch_delete_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchDeleteTestCases', + request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['batch_delete_test_cases'] + + @property + def get_test_case(self) -> Callable[ + [test_case.GetTestCaseRequest], + Awaitable[test_case.TestCase]]: + r"""Return a callable for the get test case method over gRPC. + + Gets a test case. + + Returns: + Callable[[~.GetTestCaseRequest], + Awaitable[~.TestCase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case' not in self._stubs: + self._stubs['get_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCase', + request_serializer=test_case.GetTestCaseRequest.serialize, + response_deserializer=test_case.TestCase.deserialize, + ) + return self._stubs['get_test_case'] + + @property + def create_test_case(self) -> Callable[ + [gcdc_test_case.CreateTestCaseRequest], + Awaitable[gcdc_test_case.TestCase]]: + r"""Return a callable for the create test case method over gRPC. + + Creates a test case for the given agent. + + Returns: + Callable[[~.CreateTestCaseRequest], + Awaitable[~.TestCase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_test_case' not in self._stubs: + self._stubs['create_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/CreateTestCase', + request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['create_test_case'] + + @property + def update_test_case(self) -> Callable[ + [gcdc_test_case.UpdateTestCaseRequest], + Awaitable[gcdc_test_case.TestCase]]: + r"""Return a callable for the update test case method over gRPC. + + Updates the specified test case. + + Returns: + Callable[[~.UpdateTestCaseRequest], + Awaitable[~.TestCase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_test_case' not in self._stubs: + self._stubs['update_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/UpdateTestCase', + request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize, + response_deserializer=gcdc_test_case.TestCase.deserialize, + ) + return self._stubs['update_test_case'] + + @property + def run_test_case(self) -> Callable[ + [test_case.RunTestCaseRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run test case method over gRPC. + + Kicks off a test case run. + + Returns: + Callable[[~.RunTestCaseRequest], + 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 'run_test_case' not in self._stubs: + self._stubs['run_test_case'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/RunTestCase', + request_serializer=test_case.RunTestCaseRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_test_case'] + + @property + def batch_run_test_cases(self) -> Callable[ + [test_case.BatchRunTestCasesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the batch run test cases method over gRPC. + + Kicks off a batch run of test cases. + + Returns: + Callable[[~.BatchRunTestCasesRequest], + 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_run_test_cases' not in self._stubs: + self._stubs['batch_run_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchRunTestCases', + request_serializer=test_case.BatchRunTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['batch_run_test_cases'] + + @property + def calculate_coverage(self) -> Callable[ + [test_case.CalculateCoverageRequest], + Awaitable[test_case.CalculateCoverageResponse]]: + r"""Return a callable for the calculate coverage method over gRPC. + + Calculates the test coverage for an agent. + + Returns: + Callable[[~.CalculateCoverageRequest], + Awaitable[~.CalculateCoverageResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'calculate_coverage' not in self._stubs: + self._stubs['calculate_coverage'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/CalculateCoverage', + request_serializer=test_case.CalculateCoverageRequest.serialize, + response_deserializer=test_case.CalculateCoverageResponse.deserialize, + ) + return self._stubs['calculate_coverage'] + + @property + def import_test_cases(self) -> Callable[ + [test_case.ImportTestCasesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import test cases method over gRPC. + + Imports the test cases from a Cloud Storage bucket or + a local file. It always creates new test cases and won't + overwite any existing ones. The provided ID in the + imported test case is neglected. + + Returns: + Callable[[~.ImportTestCasesRequest], + 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_test_cases' not in self._stubs: + self._stubs['import_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/ImportTestCases', + request_serializer=test_case.ImportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_test_cases'] + + @property + def export_test_cases(self) -> Callable[ + [test_case.ExportTestCasesRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export test cases method over gRPC. + + Exports the test cases under the agent to a Cloud + Storage bucket or a local file. Filter can be applied to + export a subset of test cases. + + Returns: + Callable[[~.ExportTestCasesRequest], + 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_test_cases' not in self._stubs: + self._stubs['export_test_cases'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/ExportTestCases', + request_serializer=test_case.ExportTestCasesRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_test_cases'] + + @property + def list_test_case_results(self) -> Callable[ + [test_case.ListTestCaseResultsRequest], + Awaitable[test_case.ListTestCaseResultsResponse]]: + r"""Return a callable for the list test case results method over gRPC. + + Fetches a list of results for a given test case. + + Returns: + Callable[[~.ListTestCaseResultsRequest], + Awaitable[~.ListTestCaseResultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_test_case_results' not in self._stubs: + self._stubs['list_test_case_results'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/ListTestCaseResults', + request_serializer=test_case.ListTestCaseResultsRequest.serialize, + response_deserializer=test_case.ListTestCaseResultsResponse.deserialize, + ) + return self._stubs['list_test_case_results'] + + @property + def get_test_case_result(self) -> Callable[ + [test_case.GetTestCaseResultRequest], + Awaitable[test_case.TestCaseResult]]: + r"""Return a callable for the get test case result method over gRPC. + + Gets a test case result. + + Returns: + Callable[[~.GetTestCaseResultRequest], + Awaitable[~.TestCaseResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_test_case_result' not in self._stubs: + self._stubs['get_test_case_result'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCaseResult', + request_serializer=test_case.GetTestCaseResultRequest.serialize, + response_deserializer=test_case.TestCaseResult.deserialize, + ) + return self._stubs['get_test_case_result'] + + +__all__ = ( + 'TestCasesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py new file mode 100644 index 00000000..8e43702f --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__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 TransitionRouteGroupsClient +from .async_client import TransitionRouteGroupsAsyncClient + +__all__ = ( + 'TransitionRouteGroupsClient', + 'TransitionRouteGroupsAsyncClient', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py new file mode 100644 index 00000000..0012852d --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py @@ -0,0 +1,593 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.transition_route_groups import pagers +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import transition_route_group +from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport +from .client import TransitionRouteGroupsClient + + +class TransitionRouteGroupsAsyncClient: + """Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + """ + + _client: TransitionRouteGroupsClient + + DEFAULT_ENDPOINT = TransitionRouteGroupsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TransitionRouteGroupsClient.DEFAULT_MTLS_ENDPOINT + + flow_path = staticmethod(TransitionRouteGroupsClient.flow_path) + parse_flow_path = staticmethod(TransitionRouteGroupsClient.parse_flow_path) + intent_path = staticmethod(TransitionRouteGroupsClient.intent_path) + parse_intent_path = staticmethod(TransitionRouteGroupsClient.parse_intent_path) + page_path = staticmethod(TransitionRouteGroupsClient.page_path) + parse_page_path = staticmethod(TransitionRouteGroupsClient.parse_page_path) + transition_route_group_path = staticmethod(TransitionRouteGroupsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod(TransitionRouteGroupsClient.parse_transition_route_group_path) + webhook_path = staticmethod(TransitionRouteGroupsClient.webhook_path) + parse_webhook_path = staticmethod(TransitionRouteGroupsClient.parse_webhook_path) + common_billing_account_path = staticmethod(TransitionRouteGroupsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TransitionRouteGroupsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TransitionRouteGroupsClient.common_folder_path) + parse_common_folder_path = staticmethod(TransitionRouteGroupsClient.parse_common_folder_path) + common_organization_path = staticmethod(TransitionRouteGroupsClient.common_organization_path) + parse_common_organization_path = staticmethod(TransitionRouteGroupsClient.parse_common_organization_path) + common_project_path = staticmethod(TransitionRouteGroupsClient.common_project_path) + parse_common_project_path = staticmethod(TransitionRouteGroupsClient.parse_common_project_path) + common_location_path = staticmethod(TransitionRouteGroupsClient.common_location_path) + parse_common_location_path = staticmethod(TransitionRouteGroupsClient.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: + TransitionRouteGroupsAsyncClient: The constructed client. + """ + return TransitionRouteGroupsClient.from_service_account_info.__func__(TransitionRouteGroupsAsyncClient, 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: + TransitionRouteGroupsAsyncClient: The constructed client. + """ + return TransitionRouteGroupsClient.from_service_account_file.__func__(TransitionRouteGroupsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> TransitionRouteGroupsTransport: + """Returns the transport used by the client instance. + + Returns: + TransitionRouteGroupsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(TransitionRouteGroupsClient).get_transport_class, type(TransitionRouteGroupsClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, TransitionRouteGroupsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the transition route groups 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, ~.TransitionRouteGroupsTransport]): 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 = TransitionRouteGroupsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_transition_route_groups(self, + request: transition_route_group.ListTransitionRouteGroupsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransitionRouteGroupsAsyncPager: + r"""Returns the list of all transition route groups in + the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsRequest`): + The request object. The request message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. + parent (:class:`str`): + Required. The flow to list all transition route groups + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.pagers.ListTransitionRouteGroupsAsyncPager: + The response message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. + + 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_transition_route_groups, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListTransitionRouteGroupsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_transition_route_group(self, + request: transition_route_group.GetTransitionRouteGroupRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transition_route_group.TransitionRouteGroup: + r"""Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.GetTransitionRouteGroup]. + name (:class:`str`): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3beta1.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = transition_route_group.GetTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_transition_route_group(self, + request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, + *, + parent: str = None, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + in the specified flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.CreateTransitionRouteGroup]. + parent (:class:`str`): + Required. The flow to create an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + transition_route_group (:class:`google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup`): + Required. The transition route group + to create. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3beta1.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, transition_route_group]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if transition_route_group is not None: + request.transition_route_group = transition_route_group + + # 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_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_transition_route_group(self, + request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, + *, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.UpdateTransitionRouteGroup]. + transition_route_group (:class:`google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup`): + Required. The transition route group + to update. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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.dialogflowcx_v3beta1.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3beta1.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([transition_route_group, 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 = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if transition_route_group is not None: + request.transition_route_group = transition_route_group + if update_mask is not None: + 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_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("transition_route_group.name", request.transition_route_group.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_transition_route_group(self, + request: transition_route_group.DeleteTransitionRouteGroupRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteTransitionRouteGroupRequest`): + The request object. The request message for + [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.DeleteTransitionRouteGroup]. + name (:class:`str`): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + to delete. Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = transition_route_group.DeleteTransitionRouteGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_transition_route_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TransitionRouteGroupsAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py new file mode 100644 index 00000000..5e543b07 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/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.dialogflowcx_v3beta1.services.transition_route_groups import pagers +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import transition_route_group +from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TransitionRouteGroupsGrpcTransport +from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport + + +class TransitionRouteGroupsClientMeta(type): + """Metaclass for the TransitionRouteGroups 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[TransitionRouteGroupsTransport]] + _transport_registry["grpc"] = TransitionRouteGroupsGrpcTransport + _transport_registry["grpc_asyncio"] = TransitionRouteGroupsGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[TransitionRouteGroupsTransport]: + """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 TransitionRouteGroupsClient(metaclass=TransitionRouteGroupsClientMeta): + """Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + """ + + @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: + TransitionRouteGroupsClient: 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: + TransitionRouteGroupsClient: 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) -> TransitionRouteGroupsTransport: + """Returns the transport used by the client instance. + + Returns: + TransitionRouteGroupsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def flow_path(project: str,location: str,agent: str,flow: str,) -> str: + """Returns a fully-qualified flow string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + + @staticmethod + def parse_flow_path(path: str) -> Dict[str,str]: + """Parses a flow path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def intent_path(project: str,location: str,agent: str,intent: str,) -> str: + """Returns a fully-qualified intent string.""" + return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + + @staticmethod + def parse_intent_path(path: str) -> Dict[str,str]: + """Parses a intent path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: + """Returns a fully-qualified page string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + + @staticmethod + def parse_page_path(path: str) -> Dict[str,str]: + """Parses a page path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str,str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, TransitionRouteGroupsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the transition route groups 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, TransitionRouteGroupsTransport]): 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, TransitionRouteGroupsTransport): + # transport is a TransitionRouteGroupsTransport 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_transition_route_groups(self, + request: transition_route_group.ListTransitionRouteGroupsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListTransitionRouteGroupsPager: + r"""Returns the list of all transition route groups in + the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsRequest): + The request object. The request message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. + parent (str): + Required. The flow to list all transition route groups + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.pagers.ListTransitionRouteGroupsPager: + The response message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. + + 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 transition_route_group.ListTransitionRouteGroupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, transition_route_group.ListTransitionRouteGroupsRequest): + request = transition_route_group.ListTransitionRouteGroupsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_transition_route_groups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListTransitionRouteGroupsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_transition_route_group(self, + request: transition_route_group.GetTransitionRouteGroupRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> transition_route_group.TransitionRouteGroup: + r"""Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetTransitionRouteGroupRequest): + The request object. The request message for + [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.GetTransitionRouteGroup]. + name (str): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3beta1.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 transition_route_group.GetTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, transition_route_group.GetTransitionRouteGroupRequest): + request = transition_route_group.GetTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_transition_route_group] + + # Certain fields should be provided 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_transition_route_group(self, + request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, + *, + parent: str = None, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + in the specified flow. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateTransitionRouteGroupRequest): + The request object. The request message for + [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.CreateTransitionRouteGroup]. + parent (str): + Required. The flow to create an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + transition_route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): + Required. The transition route group + to create. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3beta1.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, transition_route_group]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_transition_route_group.CreateTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_transition_route_group.CreateTransitionRouteGroupRequest): + request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if transition_route_group is not None: + request.transition_route_group = transition_route_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_transition_route_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_transition_route_group(self, + request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, + *, + transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_transition_route_group.TransitionRouteGroup: + r"""Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateTransitionRouteGroupRequest): + The request object. The request message for + [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.UpdateTransitionRouteGroup]. + transition_route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): + Required. The transition route group + to update. + + This corresponds to the ``transition_route_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.dialogflowcx_v3beta1.types.TransitionRouteGroup: + An TransitionRouteGroup represents a group of + [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] + to be used by a + [Page][google.cloud.dialogflow.cx.v3beta1.Page]. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([transition_route_group, 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 gcdc_transition_route_group.UpdateTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): + request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if transition_route_group is not None: + request.transition_route_group = transition_route_group + if update_mask is not None: + 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_transition_route_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("transition_route_group.name", request.transition_route_group.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_transition_route_group(self, + request: transition_route_group.DeleteTransitionRouteGroupRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.DeleteTransitionRouteGroupRequest): + The request object. The request message for + [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.DeleteTransitionRouteGroup]. + name (str): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + to delete. Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 transition_route_group.DeleteTransitionRouteGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, transition_route_group.DeleteTransitionRouteGroupRequest): + request = transition_route_group.DeleteTransitionRouteGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_transition_route_group] + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "TransitionRouteGroupsClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py new file mode 100644 index 00000000..13978441 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/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.dialogflowcx_v3beta1.types import transition_route_group + + +class ListTransitionRouteGroupsPager: + """A pager for iterating through ``list_transition_route_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``transition_route_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTransitionRouteGroups`` requests and continue to iterate + through the ``transition_route_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse` + 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[..., transition_route_group.ListTransitionRouteGroupsResponse], + request: transition_route_group.ListTransitionRouteGroupsRequest, + response: transition_route_group.ListTransitionRouteGroupsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse): + 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[transition_route_group.ListTransitionRouteGroupsResponse]: + 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[transition_route_group.TransitionRouteGroup]: + for page in self.pages: + yield from page.transition_route_groups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTransitionRouteGroupsAsyncPager: + """A pager for iterating through ``list_transition_route_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``transition_route_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTransitionRouteGroups`` requests and continue to iterate + through the ``transition_route_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse` + 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[transition_route_group.ListTransitionRouteGroupsResponse]], + request: transition_route_group.ListTransitionRouteGroupsRequest, + response: transition_route_group.ListTransitionRouteGroupsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse): + 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[transition_route_group.ListTransitionRouteGroupsResponse]: + 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[transition_route_group.TransitionRouteGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.transition_route_groups: + 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py new file mode 100644 index 00000000..50e891f2 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/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 TransitionRouteGroupsTransport +from .grpc import TransitionRouteGroupsGrpcTransport +from .grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TransitionRouteGroupsTransport]] +_transport_registry['grpc'] = TransitionRouteGroupsGrpcTransport +_transport_registry['grpc_asyncio'] = TransitionRouteGroupsGrpcAsyncIOTransport + +__all__ = ( + 'TransitionRouteGroupsTransport', + 'TransitionRouteGroupsGrpcTransport', + 'TransitionRouteGroupsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py new file mode 100644 index 00000000..e9ccb887 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/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.dialogflowcx_v3beta1.types import transition_route_group +from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-dialogflowcx', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class TransitionRouteGroupsTransport(abc.ABC): + """Abstract transport class for TransitionRouteGroups.""" + + 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_transition_route_groups: gapic_v1.method.wrap_method( + self.list_transition_route_groups, + default_timeout=None, + client_info=client_info, + ), + self.get_transition_route_group: gapic_v1.method.wrap_method( + self.get_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + self.create_transition_route_group: gapic_v1.method.wrap_method( + self.create_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + self.update_transition_route_group: gapic_v1.method.wrap_method( + self.update_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + self.delete_transition_route_group: gapic_v1.method.wrap_method( + self.delete_transition_route_group, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_transition_route_groups(self) -> Callable[ + [transition_route_group.ListTransitionRouteGroupsRequest], + Union[ + transition_route_group.ListTransitionRouteGroupsResponse, + Awaitable[transition_route_group.ListTransitionRouteGroupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_transition_route_group(self) -> Callable[ + [transition_route_group.GetTransitionRouteGroupRequest], + Union[ + transition_route_group.TransitionRouteGroup, + Awaitable[transition_route_group.TransitionRouteGroup] + ]]: + raise NotImplementedError() + + @property + def create_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], + Union[ + gcdc_transition_route_group.TransitionRouteGroup, + Awaitable[gcdc_transition_route_group.TransitionRouteGroup] + ]]: + raise NotImplementedError() + + @property + def update_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], + Union[ + gcdc_transition_route_group.TransitionRouteGroup, + Awaitable[gcdc_transition_route_group.TransitionRouteGroup] + ]]: + raise NotImplementedError() + + @property + def delete_transition_route_group(self) -> Callable[ + [transition_route_group.DeleteTransitionRouteGroupRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'TransitionRouteGroupsTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py new file mode 100644 index 00000000..e67cd5a7 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/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.dialogflowcx_v3beta1.types import transition_route_group +from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import empty_pb2 # type: ignore +from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO + + +class TransitionRouteGroupsGrpcTransport(TransitionRouteGroupsTransport): + """gRPC backend transport for TransitionRouteGroups. + + Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + 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_transition_route_groups(self) -> Callable[ + [transition_route_group.ListTransitionRouteGroupsRequest], + transition_route_group.ListTransitionRouteGroupsResponse]: + r"""Return a callable for the list transition route groups method over gRPC. + + Returns the list of all transition route groups in + the specified flow. + + Returns: + Callable[[~.ListTransitionRouteGroupsRequest], + ~.ListTransitionRouteGroupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_transition_route_groups' not in self._stubs: + self._stubs['list_transition_route_groups'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/ListTransitionRouteGroups', + request_serializer=transition_route_group.ListTransitionRouteGroupsRequest.serialize, + response_deserializer=transition_route_group.ListTransitionRouteGroupsResponse.deserialize, + ) + return self._stubs['list_transition_route_groups'] + + @property + def get_transition_route_group(self) -> Callable[ + [transition_route_group.GetTransitionRouteGroupRequest], + transition_route_group.TransitionRouteGroup]: + r"""Return a callable for the get transition route group method over gRPC. + + Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Returns: + Callable[[~.GetTransitionRouteGroupRequest], + ~.TransitionRouteGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_transition_route_group' not in self._stubs: + self._stubs['get_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/GetTransitionRouteGroup', + request_serializer=transition_route_group.GetTransitionRouteGroupRequest.serialize, + response_deserializer=transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['get_transition_route_group'] + + @property + def create_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], + gcdc_transition_route_group.TransitionRouteGroup]: + r"""Return a callable for the create transition route group method over gRPC. + + Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + in the specified flow. + + Returns: + Callable[[~.CreateTransitionRouteGroupRequest], + ~.TransitionRouteGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: + self._stubs['create_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/CreateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.CreateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['create_transition_route_group'] + + @property + def update_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], + gcdc_transition_route_group.TransitionRouteGroup]: + r"""Return a callable for the update transition route group method over gRPC. + + Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Returns: + Callable[[~.UpdateTransitionRouteGroupRequest], + ~.TransitionRouteGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: + self._stubs['update_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/UpdateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['update_transition_route_group'] + + @property + def delete_transition_route_group(self) -> Callable[ + [transition_route_group.DeleteTransitionRouteGroupRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete transition route group method over gRPC. + + Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Returns: + Callable[[~.DeleteTransitionRouteGroupRequest], + ~.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_transition_route_group' not in self._stubs: + self._stubs['delete_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/DeleteTransitionRouteGroup', + request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transition_route_group'] + + +__all__ = ( + 'TransitionRouteGroupsGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py new file mode 100644 index 00000000..ca567335 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/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.dialogflowcx_v3beta1.types import transition_route_group +from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group +from google.protobuf import empty_pb2 # type: ignore +from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO +from .grpc import TransitionRouteGroupsGrpcTransport + + +class TransitionRouteGroupsGrpcAsyncIOTransport(TransitionRouteGroupsTransport): + """gRPC AsyncIO backend transport for TransitionRouteGroups. + + Service for managing + [TransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + 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_transition_route_groups(self) -> Callable[ + [transition_route_group.ListTransitionRouteGroupsRequest], + Awaitable[transition_route_group.ListTransitionRouteGroupsResponse]]: + r"""Return a callable for the list transition route groups method over gRPC. + + Returns the list of all transition route groups in + the specified flow. + + Returns: + Callable[[~.ListTransitionRouteGroupsRequest], + Awaitable[~.ListTransitionRouteGroupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_transition_route_groups' not in self._stubs: + self._stubs['list_transition_route_groups'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/ListTransitionRouteGroups', + request_serializer=transition_route_group.ListTransitionRouteGroupsRequest.serialize, + response_deserializer=transition_route_group.ListTransitionRouteGroupsResponse.deserialize, + ) + return self._stubs['list_transition_route_groups'] + + @property + def get_transition_route_group(self) -> Callable[ + [transition_route_group.GetTransitionRouteGroupRequest], + Awaitable[transition_route_group.TransitionRouteGroup]]: + r"""Return a callable for the get transition route group method over gRPC. + + Retrieves the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Returns: + Callable[[~.GetTransitionRouteGroupRequest], + Awaitable[~.TransitionRouteGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_transition_route_group' not in self._stubs: + self._stubs['get_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/GetTransitionRouteGroup', + request_serializer=transition_route_group.GetTransitionRouteGroupRequest.serialize, + response_deserializer=transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['get_transition_route_group'] + + @property + def create_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], + Awaitable[gcdc_transition_route_group.TransitionRouteGroup]]: + r"""Return a callable for the create transition route group method over gRPC. + + Creates an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + in the specified flow. + + Returns: + Callable[[~.CreateTransitionRouteGroupRequest], + Awaitable[~.TransitionRouteGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: + self._stubs['create_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/CreateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.CreateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['create_transition_route_group'] + + @property + def update_transition_route_group(self) -> Callable[ + [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], + Awaitable[gcdc_transition_route_group.TransitionRouteGroup]]: + r"""Return a callable for the update transition route group method over gRPC. + + Updates the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Returns: + Callable[[~.UpdateTransitionRouteGroupRequest], + Awaitable[~.TransitionRouteGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: + self._stubs['update_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/UpdateTransitionRouteGroup', + request_serializer=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.serialize, + response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, + ) + return self._stubs['update_transition_route_group'] + + @property + def delete_transition_route_group(self) -> Callable[ + [transition_route_group.DeleteTransitionRouteGroupRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete transition route group method over gRPC. + + Deletes the specified + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + + Returns: + Callable[[~.DeleteTransitionRouteGroupRequest], + 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_transition_route_group' not in self._stubs: + self._stubs['delete_transition_route_group'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/DeleteTransitionRouteGroup', + request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_transition_route_group'] + + +__all__ = ( + 'TransitionRouteGroupsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py new file mode 100644 index 00000000..630246bd --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py new file mode 100644 index 00000000..13a5155c --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py @@ -0,0 +1,690 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.versions import pagers +from google.cloud.dialogflowcx_v3beta1.types import flow +from google.cloud.dialogflowcx_v3beta1.types import version +from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport +from .client import VersionsClient + + +class VersionsAsyncClient: + """Service for managing + [Versions][google.cloud.dialogflow.cx.v3beta1.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 in the specified + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListVersionsRequest`): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.Versions.ListVersions]. + parent (:class:`str`): + Required. The + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to list + all versions for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.versions.pagers.ListVersionsAsyncPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.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 + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetVersionRequest`): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.cx.v3beta1.Versions.GetVersion]. + name (:class:`str`): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity check: 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: gcdc_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcdc_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a [Version][google.cloud.dialogflow.cx.v3beta1.Version] + in the specified + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateVersionRequest`): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.CreateVersion]. + parent (:class:`str`): + Required. The + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to + create an + [Version][google.cloud.dialogflow.cx.v3beta1.Version] + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (:class:`google.cloud.dialogflowcx_v3beta1.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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.Version` + Represents a version of a flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = gcdc_version.CreateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcdc_version.Version, + metadata_type=gcdc_version.CreateVersionOperationMetadata, + ) + + # Done; return the response. + return response + + async def update_version(self, + request: gcdc_version.UpdateVersionRequest = None, + *, + version: gcdc_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]] = (), + ) -> gcdc_version.Version: + r"""Updates the specified + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateVersionRequest`): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.UpdateVersion]. + version (:class:`google.cloud.dialogflowcx_v3beta1.types.Version`): + Required. The version to update. + 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. + Currently only ``description`` and ``display_name`` can + 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.dialogflowcx_v3beta1.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity 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 = gcdc_version.UpdateVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + if update_mask is not None: + 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"""Deletes the specified + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteVersionRequest`): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3beta1.Versions.DeleteVersion]. + name (:class:`str`): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3beta1.Version] to + delete. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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, + ) + + async def load_version(self, + request: version.LoadVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Loads resources in the specified version to the draft + flow. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.LoadVersionRequest`): + The request object. The request message for + [Versions.LoadVersion][google.cloud.dialogflow.cx.v3beta1.Versions.LoadVersion]. + name (:class:`str`): + Required. The + [Version][google.cloud.dialogflow.cx.v3beta1.Version] to + be loaded to draft flow. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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 = version.LoadVersionRequest(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.load_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, + ) + + # 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/client.py new file mode 100644 index 00000000..6d70e13b --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/client.py @@ -0,0 +1,877 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.versions import pagers +from google.cloud.dialogflowcx_v3beta1.types import flow +from google.cloud.dialogflowcx_v3beta1.types import version +from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VersionsGrpcTransport +from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport + + +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.cx.v3beta1.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,location: str,agent: str,flow: str,version: str,) -> str: + """Returns a fully-qualified version string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str,str]: + """Parses a version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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 in the specified + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListVersionsRequest): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.Versions.ListVersions]. + parent (str): + Required. The + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to list + all versions for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.versions.pagers.ListVersionsPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.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 + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetVersionRequest): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.cx.v3beta1.Versions.GetVersion]. + name (str): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity check: 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: gcdc_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcdc_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a [Version][google.cloud.dialogflow.cx.v3beta1.Version] + in the specified + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateVersionRequest): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.CreateVersion]. + parent (str): + Required. The + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to + create an + [Version][google.cloud.dialogflow.cx.v3beta1.Version] + for. Format: + ``projects//locations//agents//flows/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (google.cloud.dialogflowcx_v3beta1.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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.Version` + Represents a version of a flow. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 gcdc_version.CreateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_version.CreateVersionRequest): + request = gcdc_version.CreateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if version is not None: + 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcdc_version.Version, + metadata_type=gcdc_version.CreateVersionOperationMetadata, + ) + + # Done; return the response. + return response + + def update_version(self, + request: gcdc_version.UpdateVersionRequest = None, + *, + version: gcdc_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]] = (), + ) -> gcdc_version.Version: + r"""Updates the specified + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateVersionRequest): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.UpdateVersion]. + version (google.cloud.dialogflowcx_v3beta1.types.Version): + Required. The version to update. + 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. + Currently only ``description`` and ``display_name`` can + 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.dialogflowcx_v3beta1.types.Version: + Represents a version of a flow. + """ + # Create or coerce a protobuf request object. + # Sanity 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 gcdc_version.UpdateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_version.UpdateVersionRequest): + request = gcdc_version.UpdateVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if version is not None: + request.version = version + if update_mask is not None: + 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"""Deletes the specified + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.DeleteVersionRequest): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3beta1.Versions.DeleteVersion]. + name (str): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3beta1.Version] to + delete. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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, + ) + + def load_version(self, + request: version.LoadVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Loads resources in the specified version to the draft + flow. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.LoadVersionRequest): + The request object. The request message for + [Versions.LoadVersion][google.cloud.dialogflow.cx.v3beta1.Versions.LoadVersion]. + name (str): + Required. The + [Version][google.cloud.dialogflow.cx.v3beta1.Version] to + be loaded to draft flow. Format: + ``projects//locations//agents//flows//versions/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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 version.LoadVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, version.LoadVersionRequest): + request = version.LoadVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.load_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, + ) + + # 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "VersionsClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py new file mode 100644 index 00000000..71b9d9fa --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.types import version + + +class ListVersionsPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py new file mode 100644 index 00000000..dfb70ce9 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py new file mode 100644 index 00000000..88fcd66f --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.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. +# +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.dialogflowcx_v3beta1.types import version +from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version +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-dialogflowcx', + ).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, + ), + self.load_version: gapic_v1.method.wrap_method( + self.load_version, + 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_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[ + [gcdc_version.CreateVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_version(self) -> Callable[ + [gcdc_version.UpdateVersionRequest], + Union[ + gcdc_version.Version, + Awaitable[gcdc_version.Version] + ]]: + raise NotImplementedError() + + @property + def delete_version(self) -> Callable[ + [version.DeleteVersionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def load_version(self) -> Callable[ + [version.LoadVersionRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'VersionsTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py new file mode 100644 index 00000000..abf54494 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py @@ -0,0 +1,407 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import version +from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version +from google.longrunning import operations_pb2 # type: ignore +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.cx.v3beta1.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] = {} + 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_versions(self) -> Callable[ + [version.ListVersionsRequest], + version.ListVersionsResponse]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions in the specified + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + + 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.cx.v3beta1.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 + [Version][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcdc_version.CreateVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the create version method over gRPC. + + Creates a [Version][google.cloud.dialogflow.cx.v3beta1.Version] + in the specified + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + + Returns: + Callable[[~.CreateVersionRequest], + ~.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_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Versions/CreateVersion', + request_serializer=gcdc_version.CreateVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcdc_version.UpdateVersionRequest], + gcdc_version.Version]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + + 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.cx.v3beta1.Versions/UpdateVersion', + request_serializer=gcdc_version.UpdateVersionRequest.serialize, + response_deserializer=gcdc_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. + + Deletes the specified + [Version][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + @property + def load_version(self) -> Callable[ + [version.LoadVersionRequest], + operations_pb2.Operation]: + r"""Return a callable for the load version method over gRPC. + + Loads resources in the specified version to the draft + flow. + + Returns: + Callable[[~.LoadVersionRequest], + ~.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 'load_version' not in self._stubs: + self._stubs['load_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Versions/LoadVersion', + request_serializer=version.LoadVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['load_version'] + + +__all__ = ( + 'VersionsGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py new file mode 100644 index 00000000..4746a6d8 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py @@ -0,0 +1,411 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import version +from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import VersionsGrpcTransport + + +class VersionsGrpcAsyncIOTransport(VersionsTransport): + """gRPC AsyncIO backend transport for Versions. + + Service for managing + [Versions][google.cloud.dialogflow.cx.v3beta1.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] = {} + 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_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 in the specified + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + + 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.cx.v3beta1.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 + [Version][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Versions/GetVersion', + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs['get_version'] + + @property + def create_version(self) -> Callable[ + [gcdc_version.CreateVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create version method over gRPC. + + Creates a [Version][google.cloud.dialogflow.cx.v3beta1.Version] + in the specified + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. + + Returns: + Callable[[~.CreateVersionRequest], + 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_version' not in self._stubs: + self._stubs['create_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Versions/CreateVersion', + request_serializer=gcdc_version.CreateVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_version'] + + @property + def update_version(self) -> Callable[ + [gcdc_version.UpdateVersionRequest], + Awaitable[gcdc_version.Version]]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + + 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.cx.v3beta1.Versions/UpdateVersion', + request_serializer=gcdc_version.UpdateVersionRequest.serialize, + response_deserializer=gcdc_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. + + Deletes the specified + [Version][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Versions/DeleteVersion', + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_version'] + + @property + def load_version(self) -> Callable[ + [version.LoadVersionRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the load version method over gRPC. + + Loads resources in the specified version to the draft + flow. + + Returns: + Callable[[~.LoadVersionRequest], + 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 'load_version' not in self._stubs: + self._stubs['load_version'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Versions/LoadVersion', + request_serializer=version.LoadVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['load_version'] + + +__all__ = ( + 'VersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py new file mode 100644 index 00000000..8ace8262 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/__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 WebhooksClient +from .async_client import WebhooksAsyncClient + +__all__ = ( + 'WebhooksClient', + 'WebhooksAsyncClient', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py new file mode 100644 index 00000000..7521843b --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py @@ -0,0 +1,581 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.webhooks import pagers +from google.cloud.dialogflowcx_v3beta1.types import webhook +from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport +from .client import WebhooksClient + + +class WebhooksAsyncClient: + """Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook]. + """ + + _client: WebhooksClient + + DEFAULT_ENDPOINT = WebhooksClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WebhooksClient.DEFAULT_MTLS_ENDPOINT + + service_path = staticmethod(WebhooksClient.service_path) + parse_service_path = staticmethod(WebhooksClient.parse_service_path) + webhook_path = staticmethod(WebhooksClient.webhook_path) + parse_webhook_path = staticmethod(WebhooksClient.parse_webhook_path) + common_billing_account_path = staticmethod(WebhooksClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(WebhooksClient.parse_common_billing_account_path) + common_folder_path = staticmethod(WebhooksClient.common_folder_path) + parse_common_folder_path = staticmethod(WebhooksClient.parse_common_folder_path) + common_organization_path = staticmethod(WebhooksClient.common_organization_path) + parse_common_organization_path = staticmethod(WebhooksClient.parse_common_organization_path) + common_project_path = staticmethod(WebhooksClient.common_project_path) + parse_common_project_path = staticmethod(WebhooksClient.parse_common_project_path) + common_location_path = staticmethod(WebhooksClient.common_location_path) + parse_common_location_path = staticmethod(WebhooksClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + 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: + WebhooksAsyncClient: The constructed client. + """ + return WebhooksClient.from_service_account_info.__func__(WebhooksAsyncClient, 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: + WebhooksAsyncClient: The constructed client. + """ + return WebhooksClient.from_service_account_file.__func__(WebhooksAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WebhooksTransport: + """Returns the transport used by the client instance. + + Returns: + WebhooksTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(WebhooksClient).get_transport_class, type(WebhooksClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, WebhooksTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the webhooks 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, ~.WebhooksTransport]): 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 = WebhooksClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_webhooks(self, + request: webhook.ListWebhooksRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWebhooksAsyncPager: + r"""Returns the list of all webhooks in the specified + agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksRequest`): + The request object. The request message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. + parent (:class:`str`): + Required. The agent to list all webhooks for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.webhooks.pagers.ListWebhooksAsyncPager: + The response message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. + + 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 = webhook.ListWebhooksRequest(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_webhooks, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListWebhooksAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_webhook(self, + request: webhook.GetWebhookRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> webhook.Webhook: + r"""Retrieves the specified webhook. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetWebhookRequest`): + The request object. The request message for + [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.GetWebhook]. + name (:class:`str`): + Required. The name of the webhook. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 = webhook.GetWebhookRequest(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_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided 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_webhook(self, + request: gcdc_webhook.CreateWebhookRequest = None, + *, + parent: str = None, + webhook: gcdc_webhook.Webhook = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Creates a webhook in the specified agent. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateWebhookRequest`): + The request object. The request message for + [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook]. + parent (:class:`str`): + Required. The agent to create a webhook for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + webhook (:class:`google.cloud.dialogflowcx_v3beta1.types.Webhook`): + Required. The webhook to create. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, webhook]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = gcdc_webhook.CreateWebhookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if webhook is not None: + request.webhook = webhook + + # 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_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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_webhook(self, + request: gcdc_webhook.UpdateWebhookRequest = None, + *, + webhook: gcdc_webhook.Webhook = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Updates the specified webhook. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateWebhookRequest`): + The request object. The request message for + [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook]. + webhook (:class:`google.cloud.dialogflowcx_v3beta1.types.Webhook`): + Required. The webhook to update. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + 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.dialogflowcx_v3beta1.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([webhook, 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 = gcdc_webhook.UpdateWebhookRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if webhook is not None: + request.webhook = webhook + if update_mask is not None: + 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_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("webhook.name", request.webhook.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_webhook(self, + request: webhook.DeleteWebhookRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified webhook. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteWebhookRequest`): + The request object. The request message for + [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.DeleteWebhook]. + name (:class:`str`): + Required. The name of the webhook to delete. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = webhook.DeleteWebhookRequest(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_webhook, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebhooksAsyncClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py new file mode 100644 index 00000000..15bd73c4 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py @@ -0,0 +1,777 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.webhooks import pagers +from google.cloud.dialogflowcx_v3beta1.types import webhook +from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import WebhooksGrpcTransport +from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport + + +class WebhooksClientMeta(type): + """Metaclass for the Webhooks 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[WebhooksTransport]] + _transport_registry["grpc"] = WebhooksGrpcTransport + _transport_registry["grpc_asyncio"] = WebhooksGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[WebhooksTransport]: + """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 WebhooksClient(metaclass=WebhooksClientMeta): + """Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook]. + """ + + @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: + WebhooksClient: 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: + WebhooksClient: 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) -> WebhooksTransport: + """Returns the transport used by the client instance. + + Returns: + WebhooksTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def service_path(project: str,location: str,namespace: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: + """Returns a fully-qualified webhook string.""" + return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + + @staticmethod + def parse_webhook_path(path: str) -> Dict[str,str]: + """Parses a webhook path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, WebhooksTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the webhooks 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, WebhooksTransport]): 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, WebhooksTransport): + # transport is a WebhooksTransport 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_webhooks(self, + request: webhook.ListWebhooksRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListWebhooksPager: + r"""Returns the list of all webhooks in the specified + agent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksRequest): + The request object. The request message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. + parent (str): + Required. The agent to list all webhooks for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.webhooks.pagers.ListWebhooksPager: + The response message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. + + 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 webhook.ListWebhooksRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, webhook.ListWebhooksRequest): + request = webhook.ListWebhooksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_webhooks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListWebhooksPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_webhook(self, + request: webhook.GetWebhookRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> webhook.Webhook: + r"""Retrieves the specified webhook. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetWebhookRequest): + The request object. The request message for + [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.GetWebhook]. + name (str): + Required. The name of the webhook. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: 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 webhook.GetWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, webhook.GetWebhookRequest): + request = webhook.GetWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_webhook] + + # Certain fields should be provided 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_webhook(self, + request: gcdc_webhook.CreateWebhookRequest = None, + *, + parent: str = None, + webhook: gcdc_webhook.Webhook = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Creates a webhook in the specified agent. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.CreateWebhookRequest): + The request object. The request message for + [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook]. + parent (str): + Required. The agent to create a webhook for. Format: + ``projects//locations//agents/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + webhook (google.cloud.dialogflowcx_v3beta1.types.Webhook): + Required. The webhook to create. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, webhook]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a gcdc_webhook.CreateWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_webhook.CreateWebhookRequest): + request = gcdc_webhook.CreateWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if webhook is not None: + request.webhook = webhook + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_webhook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_webhook(self, + request: gcdc_webhook.UpdateWebhookRequest = None, + *, + webhook: gcdc_webhook.Webhook = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcdc_webhook.Webhook: + r"""Updates the specified webhook. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.UpdateWebhookRequest): + The request object. The request message for + [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook]. + webhook (google.cloud.dialogflowcx_v3beta1.types.Webhook): + Required. The webhook to update. + This corresponds to the ``webhook`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.dialogflowcx_v3beta1.types.Webhook: + Webhooks host the developer's + business logic. During a session, + webhooks allow the developer to use the + data extracted by Dialogflow's natural + language processing to generate dynamic + responses, validate collected data, or + trigger actions on the backend. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([webhook, 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 gcdc_webhook.UpdateWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcdc_webhook.UpdateWebhookRequest): + request = gcdc_webhook.UpdateWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if webhook is not None: + request.webhook = webhook + if update_mask is not None: + 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_webhook] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("webhook.name", request.webhook.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_webhook(self, + request: webhook.DeleteWebhookRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified webhook. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.DeleteWebhookRequest): + The request object. The request message for + [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.DeleteWebhook]. + name (str): + Required. The name of the webhook to delete. Format: + ``projects//locations//agents//webhooks/``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 webhook.DeleteWebhookRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, webhook.DeleteWebhookRequest): + request = webhook.DeleteWebhookRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_webhook] + + # Certain fields should be 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-dialogflowcx", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "WebhooksClient", +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py new file mode 100644 index 00000000..460d4218 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/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.dialogflowcx_v3beta1.types import webhook + + +class ListWebhooksPager: + """A pager for iterating through ``list_webhooks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``webhooks`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWebhooks`` requests and continue to iterate + through the ``webhooks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse` + 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[..., webhook.ListWebhooksResponse], + request: webhook.ListWebhooksRequest, + response: webhook.ListWebhooksResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse): + 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 = webhook.ListWebhooksRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[webhook.ListWebhooksResponse]: + 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[webhook.Webhook]: + for page in self.pages: + yield from page.webhooks + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWebhooksAsyncPager: + """A pager for iterating through ``list_webhooks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``webhooks`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWebhooks`` requests and continue to iterate + through the ``webhooks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse` + 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[webhook.ListWebhooksResponse]], + request: webhook.ListWebhooksRequest, + response: webhook.ListWebhooksResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse): + 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 = webhook.ListWebhooksRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[webhook.ListWebhooksResponse]: + 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[webhook.Webhook]: + async def async_generator(): + async for page in self.pages: + for response in page.webhooks: + 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py new file mode 100644 index 00000000..6006a6e7 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/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 WebhooksTransport +from .grpc import WebhooksGrpcTransport +from .grpc_asyncio import WebhooksGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WebhooksTransport]] +_transport_registry['grpc'] = WebhooksGrpcTransport +_transport_registry['grpc_asyncio'] = WebhooksGrpcAsyncIOTransport + +__all__ = ( + 'WebhooksTransport', + 'WebhooksGrpcTransport', + 'WebhooksGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py new file mode 100644 index 00000000..7b811c5c --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/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.dialogflowcx_v3beta1.types import webhook +from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook +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-dialogflowcx', + ).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 WebhooksTransport(abc.ABC): + """Abstract transport class for Webhooks.""" + + 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_webhooks: gapic_v1.method.wrap_method( + self.list_webhooks, + default_timeout=None, + client_info=client_info, + ), + self.get_webhook: gapic_v1.method.wrap_method( + self.get_webhook, + default_timeout=None, + client_info=client_info, + ), + self.create_webhook: gapic_v1.method.wrap_method( + self.create_webhook, + default_timeout=None, + client_info=client_info, + ), + self.update_webhook: gapic_v1.method.wrap_method( + self.update_webhook, + default_timeout=None, + client_info=client_info, + ), + self.delete_webhook: gapic_v1.method.wrap_method( + self.delete_webhook, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def list_webhooks(self) -> Callable[ + [webhook.ListWebhooksRequest], + Union[ + webhook.ListWebhooksResponse, + Awaitable[webhook.ListWebhooksResponse] + ]]: + raise NotImplementedError() + + @property + def get_webhook(self) -> Callable[ + [webhook.GetWebhookRequest], + Union[ + webhook.Webhook, + Awaitable[webhook.Webhook] + ]]: + raise NotImplementedError() + + @property + def create_webhook(self) -> Callable[ + [gcdc_webhook.CreateWebhookRequest], + Union[ + gcdc_webhook.Webhook, + Awaitable[gcdc_webhook.Webhook] + ]]: + raise NotImplementedError() + + @property + def update_webhook(self) -> Callable[ + [gcdc_webhook.UpdateWebhookRequest], + Union[ + gcdc_webhook.Webhook, + Awaitable[gcdc_webhook.Webhook] + ]]: + raise NotImplementedError() + + @property + def delete_webhook(self) -> Callable[ + [webhook.DeleteWebhookRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'WebhooksTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py new file mode 100644 index 00000000..b860d115 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/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.dialogflowcx_v3beta1.types import webhook +from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook +from google.protobuf import empty_pb2 # type: ignore +from .base import WebhooksTransport, DEFAULT_CLIENT_INFO + + +class WebhooksGrpcTransport(WebhooksTransport): + """gRPC backend transport for Webhooks. + + Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook]. + + 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_webhooks(self) -> Callable[ + [webhook.ListWebhooksRequest], + webhook.ListWebhooksResponse]: + r"""Return a callable for the list webhooks method over gRPC. + + Returns the list of all webhooks in the specified + agent. + + Returns: + Callable[[~.ListWebhooksRequest], + ~.ListWebhooksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_webhooks' not in self._stubs: + self._stubs['list_webhooks'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Webhooks/ListWebhooks', + request_serializer=webhook.ListWebhooksRequest.serialize, + response_deserializer=webhook.ListWebhooksResponse.deserialize, + ) + return self._stubs['list_webhooks'] + + @property + def get_webhook(self) -> Callable[ + [webhook.GetWebhookRequest], + webhook.Webhook]: + r"""Return a callable for the get webhook method over gRPC. + + Retrieves the specified webhook. + + Returns: + Callable[[~.GetWebhookRequest], + ~.Webhook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_webhook' not in self._stubs: + self._stubs['get_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Webhooks/GetWebhook', + request_serializer=webhook.GetWebhookRequest.serialize, + response_deserializer=webhook.Webhook.deserialize, + ) + return self._stubs['get_webhook'] + + @property + def create_webhook(self) -> Callable[ + [gcdc_webhook.CreateWebhookRequest], + gcdc_webhook.Webhook]: + r"""Return a callable for the create webhook method over gRPC. + + Creates a webhook in the specified agent. + + Returns: + Callable[[~.CreateWebhookRequest], + ~.Webhook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_webhook' not in self._stubs: + self._stubs['create_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Webhooks/CreateWebhook', + request_serializer=gcdc_webhook.CreateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['create_webhook'] + + @property + def update_webhook(self) -> Callable[ + [gcdc_webhook.UpdateWebhookRequest], + gcdc_webhook.Webhook]: + r"""Return a callable for the update webhook method over gRPC. + + Updates the specified webhook. + + Returns: + Callable[[~.UpdateWebhookRequest], + ~.Webhook]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_webhook' not in self._stubs: + self._stubs['update_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Webhooks/UpdateWebhook', + request_serializer=gcdc_webhook.UpdateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['update_webhook'] + + @property + def delete_webhook(self) -> Callable[ + [webhook.DeleteWebhookRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete webhook method over gRPC. + + Deletes the specified webhook. + + Returns: + Callable[[~.DeleteWebhookRequest], + ~.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_webhook' not in self._stubs: + self._stubs['delete_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Webhooks/DeleteWebhook', + request_serializer=webhook.DeleteWebhookRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_webhook'] + + +__all__ = ( + 'WebhooksGrpcTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py new file mode 100644 index 00000000..5cfd1217 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/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.dialogflowcx_v3beta1.types import webhook +from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook +from google.protobuf import empty_pb2 # type: ignore +from .base import WebhooksTransport, DEFAULT_CLIENT_INFO +from .grpc import WebhooksGrpcTransport + + +class WebhooksGrpcAsyncIOTransport(WebhooksTransport): + """gRPC AsyncIO backend transport for Webhooks. + + Service for managing + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook]. + + 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_webhooks(self) -> Callable[ + [webhook.ListWebhooksRequest], + Awaitable[webhook.ListWebhooksResponse]]: + r"""Return a callable for the list webhooks method over gRPC. + + Returns the list of all webhooks in the specified + agent. + + Returns: + Callable[[~.ListWebhooksRequest], + Awaitable[~.ListWebhooksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_webhooks' not in self._stubs: + self._stubs['list_webhooks'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Webhooks/ListWebhooks', + request_serializer=webhook.ListWebhooksRequest.serialize, + response_deserializer=webhook.ListWebhooksResponse.deserialize, + ) + return self._stubs['list_webhooks'] + + @property + def get_webhook(self) -> Callable[ + [webhook.GetWebhookRequest], + Awaitable[webhook.Webhook]]: + r"""Return a callable for the get webhook method over gRPC. + + Retrieves the specified webhook. + + Returns: + Callable[[~.GetWebhookRequest], + Awaitable[~.Webhook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_webhook' not in self._stubs: + self._stubs['get_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Webhooks/GetWebhook', + request_serializer=webhook.GetWebhookRequest.serialize, + response_deserializer=webhook.Webhook.deserialize, + ) + return self._stubs['get_webhook'] + + @property + def create_webhook(self) -> Callable[ + [gcdc_webhook.CreateWebhookRequest], + Awaitable[gcdc_webhook.Webhook]]: + r"""Return a callable for the create webhook method over gRPC. + + Creates a webhook in the specified agent. + + Returns: + Callable[[~.CreateWebhookRequest], + Awaitable[~.Webhook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_webhook' not in self._stubs: + self._stubs['create_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Webhooks/CreateWebhook', + request_serializer=gcdc_webhook.CreateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['create_webhook'] + + @property + def update_webhook(self) -> Callable[ + [gcdc_webhook.UpdateWebhookRequest], + Awaitable[gcdc_webhook.Webhook]]: + r"""Return a callable for the update webhook method over gRPC. + + Updates the specified webhook. + + Returns: + Callable[[~.UpdateWebhookRequest], + Awaitable[~.Webhook]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_webhook' not in self._stubs: + self._stubs['update_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Webhooks/UpdateWebhook', + request_serializer=gcdc_webhook.UpdateWebhookRequest.serialize, + response_deserializer=gcdc_webhook.Webhook.deserialize, + ) + return self._stubs['update_webhook'] + + @property + def delete_webhook(self) -> Callable[ + [webhook.DeleteWebhookRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete webhook method over gRPC. + + Deletes the specified webhook. + + Returns: + Callable[[~.DeleteWebhookRequest], + 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_webhook' not in self._stubs: + self._stubs['delete_webhook'] = self.grpc_channel.unary_unary( + '/google.cloud.dialogflow.cx.v3beta1.Webhooks/DeleteWebhook', + request_serializer=webhook.DeleteWebhookRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_webhook'] + + +__all__ = ( + 'WebhooksGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/__init__.py new file mode 100644 index 00000000..6b900835 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/__init__.py @@ -0,0 +1,430 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, + AgentValidationResult, + CreateAgentRequest, + DeleteAgentRequest, + ExportAgentRequest, + ExportAgentResponse, + GetAgentRequest, + GetAgentValidationResultRequest, + ListAgentsRequest, + ListAgentsResponse, + RestoreAgentRequest, + SpeechToTextSettings, + UpdateAgentRequest, + ValidateAgentRequest, +) +from .audio_config import ( + InputAudioConfig, + OutputAudioConfig, + SpeechWordInfo, + SynthesizeSpeechConfig, + VoiceSelectionParams, + AudioEncoding, + OutputAudioEncoding, + SpeechModelVariant, + SsmlVoiceGender, +) +from .entity_type import ( + CreateEntityTypeRequest, + DeleteEntityTypeRequest, + EntityType, + GetEntityTypeRequest, + ListEntityTypesRequest, + ListEntityTypesResponse, + UpdateEntityTypeRequest, +) +from .environment import ( + ContinuousTestResult, + CreateEnvironmentRequest, + DeleteEnvironmentRequest, + Environment, + GetEnvironmentRequest, + ListContinuousTestResultsRequest, + ListContinuousTestResultsResponse, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + LookupEnvironmentHistoryRequest, + LookupEnvironmentHistoryResponse, + RunContinuousTestMetadata, + RunContinuousTestRequest, + RunContinuousTestResponse, + UpdateEnvironmentRequest, +) +from .experiment import ( + CreateExperimentRequest, + DeleteExperimentRequest, + Experiment, + GetExperimentRequest, + ListExperimentsRequest, + ListExperimentsResponse, + StartExperimentRequest, + StopExperimentRequest, + UpdateExperimentRequest, + VariantsHistory, + VersionVariants, +) +from .flow import ( + CreateFlowRequest, + DeleteFlowRequest, + ExportFlowRequest, + ExportFlowResponse, + Flow, + FlowValidationResult, + GetFlowRequest, + GetFlowValidationResultRequest, + ImportFlowRequest, + ImportFlowResponse, + ListFlowsRequest, + ListFlowsResponse, + NluSettings, + TrainFlowRequest, + UpdateFlowRequest, + ValidateFlowRequest, +) +from .fulfillment import ( + Fulfillment, +) +from .intent import ( + CreateIntentRequest, + DeleteIntentRequest, + GetIntentRequest, + Intent, + ListIntentsRequest, + ListIntentsResponse, + UpdateIntentRequest, + IntentView, +) +from .page import ( + CreatePageRequest, + DeletePageRequest, + EventHandler, + Form, + GetPageRequest, + ListPagesRequest, + ListPagesResponse, + Page, + TransitionRoute, + UpdatePageRequest, +) +from .response_message import ( + ResponseMessage, +) +from .security_settings import ( + CreateSecuritySettingsRequest, + DeleteSecuritySettingsRequest, + GetSecuritySettingsRequest, + ListSecuritySettingsRequest, + ListSecuritySettingsResponse, + SecuritySettings, + UpdateSecuritySettingsRequest, +) +from .session import ( + AudioInput, + DetectIntentRequest, + DetectIntentResponse, + DtmfInput, + EventInput, + FulfillIntentRequest, + FulfillIntentResponse, + IntentInput, + Match, + MatchIntentRequest, + MatchIntentResponse, + QueryInput, + QueryParameters, + QueryResult, + SentimentAnalysisResult, + StreamingDetectIntentRequest, + StreamingDetectIntentResponse, + StreamingRecognitionResult, + TextInput, +) +from .session_entity_type import ( + CreateSessionEntityTypeRequest, + DeleteSessionEntityTypeRequest, + GetSessionEntityTypeRequest, + ListSessionEntityTypesRequest, + ListSessionEntityTypesResponse, + SessionEntityType, + UpdateSessionEntityTypeRequest, +) +from .test_case import ( + BatchDeleteTestCasesRequest, + BatchRunTestCasesMetadata, + BatchRunTestCasesRequest, + BatchRunTestCasesResponse, + CalculateCoverageRequest, + CalculateCoverageResponse, + ConversationTurn, + CreateTestCaseRequest, + ExportTestCasesMetadata, + ExportTestCasesRequest, + ExportTestCasesResponse, + GetTestCaseRequest, + GetTestCaseResultRequest, + ImportTestCasesMetadata, + ImportTestCasesRequest, + ImportTestCasesResponse, + IntentCoverage, + ListTestCaseResultsRequest, + ListTestCaseResultsResponse, + ListTestCasesRequest, + ListTestCasesResponse, + RunTestCaseMetadata, + RunTestCaseRequest, + RunTestCaseResponse, + TestCase, + TestCaseError, + TestCaseResult, + TestConfig, + TestError, + TestRunDifference, + TransitionCoverage, + TransitionRouteGroupCoverage, + UpdateTestCaseRequest, + TestResult, +) +from .transition_route_group import ( + CreateTransitionRouteGroupRequest, + DeleteTransitionRouteGroupRequest, + GetTransitionRouteGroupRequest, + ListTransitionRouteGroupsRequest, + ListTransitionRouteGroupsResponse, + TransitionRouteGroup, + UpdateTransitionRouteGroupRequest, +) +from .validation_message import ( + ResourceName, + ValidationMessage, +) +from .version import ( + CreateVersionOperationMetadata, + CreateVersionRequest, + DeleteVersionRequest, + GetVersionRequest, + ListVersionsRequest, + ListVersionsResponse, + LoadVersionRequest, + UpdateVersionRequest, + Version, +) +from .webhook import ( + CreateWebhookRequest, + DeleteWebhookRequest, + GetWebhookRequest, + ListWebhooksRequest, + ListWebhooksResponse, + PageInfo, + SessionInfo, + UpdateWebhookRequest, + Webhook, + WebhookRequest, + WebhookResponse, +) + +__all__ = ( + 'Agent', + 'AgentValidationResult', + 'CreateAgentRequest', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'GetAgentRequest', + 'GetAgentValidationResultRequest', + 'ListAgentsRequest', + 'ListAgentsResponse', + 'RestoreAgentRequest', + 'SpeechToTextSettings', + 'UpdateAgentRequest', + 'ValidateAgentRequest', + 'InputAudioConfig', + 'OutputAudioConfig', + 'SpeechWordInfo', + 'SynthesizeSpeechConfig', + 'VoiceSelectionParams', + 'AudioEncoding', + 'OutputAudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'CreateEntityTypeRequest', + 'DeleteEntityTypeRequest', + 'EntityType', + 'GetEntityTypeRequest', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'UpdateEntityTypeRequest', + 'ContinuousTestResult', + 'CreateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'Environment', + 'GetEnvironmentRequest', + 'ListContinuousTestResultsRequest', + 'ListContinuousTestResultsResponse', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LookupEnvironmentHistoryRequest', + 'LookupEnvironmentHistoryResponse', + 'RunContinuousTestMetadata', + 'RunContinuousTestRequest', + 'RunContinuousTestResponse', + 'UpdateEnvironmentRequest', + 'CreateExperimentRequest', + 'DeleteExperimentRequest', + 'Experiment', + 'GetExperimentRequest', + 'ListExperimentsRequest', + 'ListExperimentsResponse', + 'StartExperimentRequest', + 'StopExperimentRequest', + 'UpdateExperimentRequest', + 'VariantsHistory', + 'VersionVariants', + 'CreateFlowRequest', + 'DeleteFlowRequest', + 'ExportFlowRequest', + 'ExportFlowResponse', + 'Flow', + 'FlowValidationResult', + 'GetFlowRequest', + 'GetFlowValidationResultRequest', + 'ImportFlowRequest', + 'ImportFlowResponse', + 'ListFlowsRequest', + 'ListFlowsResponse', + 'NluSettings', + 'TrainFlowRequest', + 'UpdateFlowRequest', + 'ValidateFlowRequest', + 'Fulfillment', + 'CreateIntentRequest', + 'DeleteIntentRequest', + 'GetIntentRequest', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'UpdateIntentRequest', + 'IntentView', + 'CreatePageRequest', + 'DeletePageRequest', + 'EventHandler', + 'Form', + 'GetPageRequest', + 'ListPagesRequest', + 'ListPagesResponse', + 'Page', + 'TransitionRoute', + 'UpdatePageRequest', + 'ResponseMessage', + 'CreateSecuritySettingsRequest', + 'DeleteSecuritySettingsRequest', + 'GetSecuritySettingsRequest', + 'ListSecuritySettingsRequest', + 'ListSecuritySettingsResponse', + 'SecuritySettings', + 'UpdateSecuritySettingsRequest', + 'AudioInput', + 'DetectIntentRequest', + 'DetectIntentResponse', + 'DtmfInput', + 'EventInput', + 'FulfillIntentRequest', + 'FulfillIntentResponse', + 'IntentInput', + 'Match', + 'MatchIntentRequest', + 'MatchIntentResponse', + 'QueryInput', + 'QueryParameters', + 'QueryResult', + 'SentimentAnalysisResult', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'TextInput', + 'CreateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + 'GetSessionEntityTypeRequest', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'SessionEntityType', + 'UpdateSessionEntityTypeRequest', + 'BatchDeleteTestCasesRequest', + 'BatchRunTestCasesMetadata', + 'BatchRunTestCasesRequest', + 'BatchRunTestCasesResponse', + 'CalculateCoverageRequest', + 'CalculateCoverageResponse', + 'ConversationTurn', + 'CreateTestCaseRequest', + 'ExportTestCasesMetadata', + 'ExportTestCasesRequest', + 'ExportTestCasesResponse', + 'GetTestCaseRequest', + 'GetTestCaseResultRequest', + 'ImportTestCasesMetadata', + 'ImportTestCasesRequest', + 'ImportTestCasesResponse', + 'IntentCoverage', + 'ListTestCaseResultsRequest', + 'ListTestCaseResultsResponse', + 'ListTestCasesRequest', + 'ListTestCasesResponse', + 'RunTestCaseMetadata', + 'RunTestCaseRequest', + 'RunTestCaseResponse', + 'TestCase', + 'TestCaseError', + 'TestCaseResult', + 'TestConfig', + 'TestError', + 'TestRunDifference', + 'TransitionCoverage', + 'TransitionRouteGroupCoverage', + 'UpdateTestCaseRequest', + 'TestResult', + 'CreateTransitionRouteGroupRequest', + 'DeleteTransitionRouteGroupRequest', + 'GetTransitionRouteGroupRequest', + 'ListTransitionRouteGroupsRequest', + 'ListTransitionRouteGroupsResponse', + 'TransitionRouteGroup', + 'UpdateTransitionRouteGroupRequest', + 'ResourceName', + 'ValidationMessage', + 'CreateVersionOperationMetadata', + 'CreateVersionRequest', + 'DeleteVersionRequest', + 'GetVersionRequest', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'LoadVersionRequest', + 'UpdateVersionRequest', + 'Version', + 'CreateWebhookRequest', + 'DeleteWebhookRequest', + 'GetWebhookRequest', + 'ListWebhooksRequest', + 'ListWebhooksResponse', + 'PageInfo', + 'SessionInfo', + 'UpdateWebhookRequest', + 'Webhook', + 'WebhookRequest', + 'WebhookResponse', +) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/agent.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/agent.py new file mode 100644 index 00000000..5488e1a8 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/agent.py @@ -0,0 +1,491 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import flow +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'SpeechToTextSettings', + 'Agent', + 'ListAgentsRequest', + 'ListAgentsResponse', + 'GetAgentRequest', + 'CreateAgentRequest', + 'UpdateAgentRequest', + 'DeleteAgentRequest', + 'ExportAgentRequest', + 'ExportAgentResponse', + 'RestoreAgentRequest', + 'ValidateAgentRequest', + 'GetAgentValidationResultRequest', + 'AgentValidationResult', + }, +) + + +class SpeechToTextSettings(proto.Message): + r"""Settings related to speech recognition. + Attributes: + enable_speech_adaptation (bool): + Whether to use speech adaptation for speech + recognition. + """ + + enable_speech_adaptation = proto.Field( + proto.BOOL, + number=1, + ) + + +class Agent(proto.Message): + r"""Agents are best described as Natural Language Understanding (NLU) + modules that transform user requests into actionable data. You can + include agents in your app, product, or service to determine user + intent and respond to the user in a natural way. + + After you create an agent, you can add + [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], [Entity + Types][google.cloud.dialogflow.cx.v3beta1.EntityType], + [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], + [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], + [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], and so on to + manage the conversation flows.. + + Attributes: + name (str): + The unique identifier of the agent. Required for the + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent] + method. + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.CreateAgent] + populates the name automatically. Format: + ``projects//locations//agents/``. + display_name (str): + Required. The human-readable name of the + agent, unique within the location. + default_language_code (str): + Immutable. 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 + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent] + method. + supported_language_codes (Sequence[str]): + The list of all languages supported by the agent (except for + the ``default_language_code``). + time_zone (str): + Required. The time zone of the agent from the `time zone + database `__, e.g., + America/New_York, Europe/Paris. + description (str): + The description of the agent. The maximum + length is 500 characters. If exceeded, the + request is rejected. + avatar_uri (str): + The URI of the agent's avatar. Avatars are used throughout + the Dialogflow console and in the self-hosted `Web + Demo `__ + integration. + speech_to_text_settings (google.cloud.dialogflowcx_v3beta1.types.SpeechToTextSettings): + Speech recognition related settings. + start_flow (str): + Immutable. Name of the start flow in this agent. A start + flow will be automatically created when the agent is + created, and can only be deleted by deleting the agent. + Format: + ``projects//locations//agents//flows/``. + security_settings (str): + Name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + reference for the agent. Format: + ``projects//locations//securitySettings/``. + enable_stackdriver_logging (bool): + Indicates if stackdriver logging is enabled + for the agent. + enable_spell_correction (bool): + Indicates if automatic spell correction is + enabled in detect intent requests. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + default_language_code = proto.Field( + proto.STRING, + number=3, + ) + supported_language_codes = proto.RepeatedField( + proto.STRING, + number=4, + ) + time_zone = proto.Field( + proto.STRING, + number=5, + ) + description = proto.Field( + proto.STRING, + number=6, + ) + avatar_uri = proto.Field( + proto.STRING, + number=7, + ) + speech_to_text_settings = proto.Field( + proto.MESSAGE, + number=13, + message='SpeechToTextSettings', + ) + start_flow = proto.Field( + proto.STRING, + number=16, + ) + security_settings = proto.Field( + proto.STRING, + number=17, + ) + enable_stackdriver_logging = proto.Field( + proto.BOOL, + number=18, + ) + enable_spell_correction = proto.Field( + proto.BOOL, + number=20, + ) + + +class ListAgentsRequest(proto.Message): + r"""The request message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. + + Attributes: + parent (str): + Required. The location to list all agents for. 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 ListAgentsResponse(proto.Message): + r"""The response message for + [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. + + Attributes: + agents (Sequence[google.cloud.dialogflowcx_v3beta1.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 GetAgentRequest(proto.Message): + r"""The request message for + [Agents.GetAgent][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgent]. + + Attributes: + name (str): + Required. The name of the agent. Format: + ``projects//locations//agents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAgentRequest(proto.Message): + r"""The request message for + [Agents.CreateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.CreateAgent]. + + Attributes: + parent (str): + Required. The location to create a agent for. Format: + ``projects//locations/``. + agent (google.cloud.dialogflowcx_v3beta1.types.Agent): + Required. The agent to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + agent = proto.Field( + proto.MESSAGE, + number=2, + message='Agent', + ) + + +class UpdateAgentRequest(proto.Message): + r"""The request message for + [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent]. + + Attributes: + agent (google.cloud.dialogflowcx_v3beta1.types.Agent): + Required. The agent to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + 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.cx.v3beta1.Agents.DeleteAgent]. + + Attributes: + name (str): + Required. The name of the agent to delete. Format: + ``projects//locations//agents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportAgentRequest(proto.Message): + r"""The request message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. + + Attributes: + name (str): + Required. The name of the agent to export. Format: + ``projects//locations//agents/``. + 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. + environment (str): + Optional. Environment name. If not set, draft environment is + assumed. Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + ) + environment = proto.Field( + proto.STRING, + number=5, + ) + + +class ExportAgentResponse(proto.Message): + r"""The response message for + [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.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][google.cloud.dialogflow.cx.v3beta1.ExportAgentRequest]. + agent_content (bytes): + Uncompressed raw byte content for agent. + """ + + agent_uri = proto.Field( + proto.STRING, + number=1, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=2, + oneof='agent', + ) + + +class RestoreAgentRequest(proto.Message): + r"""The request message for + [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3beta1.Agents.RestoreAgent]. + + Attributes: + name (str): + Required. The name of the agent to restore into. Format: + ``projects//locations//agents/``. + agent_uri (str): + The `Google Cloud + Storage `__ URI to + restore agent from. The format of this URI must be + ``gs:///``. + agent_content (bytes): + Uncompressed raw byte content for agent. + restore_option (google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest.RestoreOption): + Agent restore mode. If not specified, ``KEEP`` is assumed. + """ + class RestoreOption(proto.Enum): + r"""Restore option.""" + RESTORE_OPTION_UNSPECIFIED = 0 + KEEP = 1 + FALLBACK = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + agent_uri = proto.Field( + proto.STRING, + number=2, + oneof='agent', + ) + agent_content = proto.Field( + proto.BYTES, + number=3, + oneof='agent', + ) + restore_option = proto.Field( + proto.ENUM, + number=5, + enum=RestoreOption, + ) + + +class ValidateAgentRequest(proto.Message): + r"""The request message for + [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ValidateAgent]. + + Attributes: + name (str): + Required. The agent to validate. Format: + ``projects//locations//agents/``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAgentValidationResultRequest(proto.Message): + r"""The request message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. + + Attributes: + name (str): + Required. The agent name. Format: + ``projects//locations//agents//validationResult``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class AgentValidationResult(proto.Message): + r"""The response message for + [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. + + Attributes: + name (str): + The unique identifier of the agent validation result. + Format: + ``projects//locations//agents//validationResult``. + flow_validation_results (Sequence[google.cloud.dialogflowcx_v3beta1.types.FlowValidationResult]): + Contains all flow validation results. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + flow_validation_results = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=flow.FlowValidationResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/audio_config.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/audio_config.py new file mode 100644 index 00000000..e7611ee0 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/audio_config.py @@ -0,0 +1,357 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cx.v3beta1', + manifest={ + 'AudioEncoding', + 'SpeechModelVariant', + 'SsmlVoiceGender', + 'OutputAudioEncoding', + 'SpeechWordInfo', + 'InputAudioConfig', + 'VoiceSelectionParams', + 'SynthesizeSpeechConfig', + 'OutputAudioConfig', + }, +) + + +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.cx.v3beta1.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 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.dialogflowcx_v3beta1.types.AudioEncoding): + Required. Audio encoding of the audio content + to process. + sample_rate_hertz (int): + Sample rate (in Hertz) of the audio content sent in the + query. Refer to `Cloud Speech API + documentation `__ + for more details. + enable_word_info (bool): + Optional. If ``true``, Dialogflow returns + [SpeechWordInfo][google.cloud.dialogflow.cx.v3beta1.SpeechWordInfo] + in + [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3beta1.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]): + Optional. 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. + model (str): + Optional. 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.dialogflowcx_v3beta1.types.SpeechModelVariant): + Optional. Which variant of the [Speech + model][google.cloud.dialogflow.cx.v3beta1.InputAudioConfig.model] + to use. + single_utterance (bool): + Optional. 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. + """ + + audio_encoding = proto.Field( + proto.ENUM, + number=1, + enum='AudioEncoding', + ) + sample_rate_hertz = proto.Field( + proto.INT32, + number=2, + ) + enable_word_info = proto.Field( + proto.BOOL, + number=13, + ) + phrase_hints = proto.RepeatedField( + proto.STRING, + number=4, + ) + model = proto.Field( + proto.STRING, + number=7, + ) + model_variant = proto.Field( + proto.ENUM, + number=10, + enum='SpeechModelVariant', + ) + single_utterance = proto.Field( + proto.BOOL, + number=8, + ) + + +class VoiceSelectionParams(proto.Message): + r"""Description of which voice to use for speech synthesis. + Attributes: + name (str): + Optional. The name of the voice. If not set, the service + will choose a voice based on the other parameters such as + language_code and + [ssml_gender][google.cloud.dialogflow.cx.v3beta1.VoiceSelectionParams.ssml_gender]. + + For the list of available voices, please refer to `Supported + voices and + languages `__. + ssml_gender (google.cloud.dialogflowcx_v3beta1.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.cx.v3beta1.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.dialogflowcx_v3beta1.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. + + Attributes: + audio_encoding (google.cloud.dialogflowcx_v3beta1.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_config (google.cloud.dialogflowcx_v3beta1.types.SynthesizeSpeechConfig): + Optional. 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', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/entity_type.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/entity_type.py new file mode 100644 index 00000000..6ad3443d --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/entity_type.py @@ -0,0 +1,425 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cx.v3beta1', + manifest={ + 'EntityType', + 'ListEntityTypesRequest', + 'ListEntityTypesResponse', + 'GetEntityTypeRequest', + 'CreateEntityTypeRequest', + 'UpdateEntityTypeRequest', + 'DeleteEntityTypeRequest', + }, +) + + +class EntityType(proto.Message): + r"""Entities are extracted from user input and represent parameters that + are meaningful to your application. For example, a date range, a + proper name such as a geographic location or landmark, and so on. + Entities represent actionable data for your application. + + When you define an entity, you can also include synonyms that all + map to that entity. For example, "soft drink", "soda", "pop", and so + on. + + There are three types of entities: + + - **System** - entities that are defined by the Dialogflow API for + common data types such as date, time, currency, and so on. A + system entity is represented by the ``EntityType`` type. + + - **Custom** - entities that are defined by you that represent + actionable data that is meaningful to your application. For + example, you could define a ``pizza.sauce`` entity for red or + white pizza sauce, a ``pizza.cheese`` entity for the different + types of cheese on a pizza, a ``pizza.topping`` entity for + different toppings, and so on. A custom entity is represented by + the ``EntityType`` type. + + - **User** - entities that are built for an individual user such as + favorites, preferences, playlists, and so on. A user entity is + represented by the + [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] + type. + + For more information about entity types, see the `Dialogflow + documentation `__. + + Attributes: + name (str): + The unique identifier of the entity type. Required for + [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.UpdateEntityType]. + Format: + ``projects//locations//agents//entityTypes/``. + display_name (str): + Required. The human-readable name of the + entity type, unique within the agent. + kind (google.cloud.dialogflowcx_v3beta1.types.EntityType.Kind): + Required. Indicates the kind of entity type. + auto_expansion_mode (google.cloud.dialogflowcx_v3beta1.types.EntityType.AutoExpansionMode): + Indicates whether the entity type can be + automatically expanded. + entities (Sequence[google.cloud.dialogflowcx_v3beta1.types.EntityType.Entity]): + The collection of entity entries associated + with the entity type. + excluded_phrases (Sequence[google.cloud.dialogflowcx_v3beta1.types.EntityType.ExcludedPhrase]): + Collection of exceptional words and phrases that shouldn't + be matched. For example, if you have a size entity type with + entry ``giant``\ (an adjective), you might consider adding + ``giants``\ (a noun) as an exclusion. If the kind of entity + type is ``KIND_MAP``, then the phrases specified by entities + and excluded phrases should be mutually exclusive. + enable_fuzzy_extraction (bool): + Enables fuzzy entity extraction during + classification. + redact (bool): + Indicates whether parameters of the entity + type should be redacted in log. If redaction is + enabled, page parameters and intent parameters + referring to the entity type will be replaced by + parameter name during logging. + """ + 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 canonical 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, + ) + + class ExcludedPhrase(proto.Message): + r"""An excluded entity phrase that should not be matched. + Attributes: + value (str): + Required. The word or phrase to be excluded. + """ + + value = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + kind = proto.Field( + proto.ENUM, + number=3, + enum=Kind, + ) + auto_expansion_mode = proto.Field( + proto.ENUM, + number=4, + enum=AutoExpansionMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Entity, + ) + excluded_phrases = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=ExcludedPhrase, + ) + enable_fuzzy_extraction = proto.Field( + proto.BOOL, + number=7, + ) + redact = proto.Field( + proto.BOOL, + number=9, + ) + + +class ListEntityTypesRequest(proto.Message): + r"""The request message for + [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.EntityTypes.ListEntityTypes]. + + Attributes: + parent (str): + Required. The agent to list all entity types for. Format: + ``projects//locations//agents/``. + language_code (str): + The language to list entity types for. The following fields + are language dependent: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + 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. + 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, + ) + 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.cx.v3beta1.EntityTypes.ListEntityTypes]. + + Attributes: + entity_types (Sequence[google.cloud.dialogflowcx_v3beta1.types.EntityType]): + The list of 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.cx.v3beta1.EntityTypes.GetEntityType]. + + Attributes: + name (str): + Required. The name of the entity type. Format: + ``projects//locations//agents//entityTypes/``. + language_code (str): + The language to retrieve the entity type for. The following + fields are language dependent: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + 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. + """ + + 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.cx.v3beta1.EntityTypes.CreateEntityType]. + + Attributes: + parent (str): + Required. The agent to create a entity type for. Format: + ``projects//locations//agents/``. + entity_type (google.cloud.dialogflowcx_v3beta1.types.EntityType): + Required. The entity type to create. + language_code (str): + The language of the following fields in ``entity_type``: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + 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, + ) + 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.cx.v3beta1.EntityTypes.UpdateEntityType]. + + Attributes: + entity_type (google.cloud.dialogflowcx_v3beta1.types.EntityType): + Required. The entity type to update. + language_code (str): + The language of the following fields in ``entity_type``: + + - ``EntityType.entities.value`` + - ``EntityType.entities.synonyms`` + - ``EntityType.excluded_phrases.value`` + + 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. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.cx.v3beta1.EntityTypes.DeleteEntityType]. + + Attributes: + name (str): + Required. The name of the entity type to delete. Format: + ``projects//locations//agents//entityTypes/``. + force (bool): + This field has no effect for entity type not being used. For + entity types that are used by intents or pages: + + - If ``force`` is set to false, an error will be returned + with message indicating the referencing resources. + - If ``force`` is set to true, Dialogflow will remove the + entity type, as well as any references to the entity type + (i.e. Page + [parameter][google.cloud.dialogflow.cx.v3beta1.Form.Parameter] + of the entity type will be changed to '@sys.any' and + intent + [parameter][google.cloud.dialogflow.cx.v3beta1.Intent.Parameter] + of the entity type will be removed). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/environment.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/environment.py new file mode 100644 index 00000000..57ea3cce --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/environment.py @@ -0,0 +1,478 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import test_case +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'Environment', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'GetEnvironmentRequest', + 'CreateEnvironmentRequest', + 'UpdateEnvironmentRequest', + 'DeleteEnvironmentRequest', + 'LookupEnvironmentHistoryRequest', + 'LookupEnvironmentHistoryResponse', + 'ContinuousTestResult', + 'RunContinuousTestRequest', + 'RunContinuousTestResponse', + 'RunContinuousTestMetadata', + 'ListContinuousTestResultsRequest', + 'ListContinuousTestResultsResponse', + }, +) + + +class Environment(proto.Message): + r"""Represents an environment for an agent. 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. + + Attributes: + name (str): + The name of the environment. Format: + ``projects//locations//agents//environments/``. + display_name (str): + Required. The human-readable name of the + environment (unique in an agent). Limit of 64 + characters. + description (str): + The human-readable description of the + environment. The maximum length is 500 + characters. If exceeded, the request is + rejected. + version_configs (Sequence[google.cloud.dialogflowcx_v3beta1.types.Environment.VersionConfig]): + Required. A list of configurations for flow versions. You + should include version configs for all flows that are + reachable from [``Start Flow``][Agent.start_flow] in the + agent. Otherwise, an error will be returned. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time of this environment. + """ + + class VersionConfig(proto.Message): + r"""Configuration for the version. + Attributes: + version (str): + Required. Format: projects//locations//agents//flows//versions/. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + version_configs = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=VersionConfig, + ) + update_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class ListEnvironmentsRequest(proto.Message): + r"""The request message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.Environments.ListEnvironments]. + + Attributes: + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to list + all environments for. Format: + ``projects//locations//agents/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 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 ListEnvironmentsResponse(proto.Message): + r"""The response message for + [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.Environments.ListEnvironments]. + + Attributes: + environments (Sequence[google.cloud.dialogflowcx_v3beta1.types.Environment]): + The list of environments. There will be a maximum number of + items returned based on the page_size field in the request. + The list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + 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.cx.v3beta1.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + for. Format: + ``projects//locations//agents/``. + environment (google.cloud.dialogflowcx_v3beta1.types.Environment): + Required. The environment to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.MESSAGE, + number=2, + message='Environment', + ) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflowcx_v3beta1.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + environment = proto.Field( + proto.MESSAGE, + number=1, + message='Environment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to delete. Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class LookupEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. + + Attributes: + name (str): + Required. Resource name of the environment to look up the + history for. Format: + ``projects//locations//agents//environments/``. + 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. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class LookupEnvironmentHistoryResponse(proto.Message): + r"""The response message for + [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. + + Attributes: + environments (Sequence[google.cloud.dialogflowcx_v3beta1.types.Environment]): + Represents a list of snapshots for an environment. Time of + the snapshots is stored in + [``update_time``][google.cloud.dialogflow.cx.v3beta1.Environment.update_time]. + 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 ContinuousTestResult(proto.Message): + r"""Represents a result from running a test case in an agent + environment. + + Attributes: + name (str): + The resource name for the continuous test result. Format: + ``projects//locations//agents//environments//continuousTestResults/``. + result (google.cloud.dialogflowcx_v3beta1.types.ContinuousTestResult.AggregatedTestResult): + The result of this continuous test run, i.e. + whether all the tests in this continuous test + run pass or not. + test_case_results (Sequence[str]): + A list of individual test case results names + in this continuous test run. + run_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the continuous testing run starts. + """ + class AggregatedTestResult(proto.Enum): + r"""The overall result for a continuous test run in an agent + environment. + """ + AGGREGATED_TEST_RESULT_UNSPECIFIED = 0 + PASSED = 1 + FAILED = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + result = proto.Field( + proto.ENUM, + number=2, + enum=AggregatedTestResult, + ) + test_case_results = proto.RepeatedField( + proto.STRING, + number=3, + ) + run_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class RunContinuousTestRequest(proto.Message): + r"""The request message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + + Attributes: + environment (str): + Required. Format: + ``projects//locations//agents//environments/``. + """ + + environment = proto.Field( + proto.STRING, + number=1, + ) + + +class RunContinuousTestResponse(proto.Message): + r"""The response message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + + Attributes: + continuous_test_result (google.cloud.dialogflowcx_v3beta1.types.ContinuousTestResult): + The result for a continuous test run. + """ + + continuous_test_result = proto.Field( + proto.MESSAGE, + number=1, + message='ContinuousTestResult', + ) + + +class RunContinuousTestMetadata(proto.Message): + r"""Metadata returned for the + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest] + long running operation. + + Attributes: + errors (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestError]): + The test errors. + """ + + errors = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=test_case.TestError, + ) + + +class ListContinuousTestResultsRequest(proto.Message): + r"""The request message for + [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3beta1.Environments.ListContinuousTestResults]. + + Attributes: + parent (str): + Required. The environment to list results for. Format: + ``projects//locations//agents// environments/``. + 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 ListContinuousTestResultsResponse(proto.Message): + r"""The response message for [Environments.ListTestCaseResults][]. + Attributes: + continuous_test_results (Sequence[google.cloud.dialogflowcx_v3beta1.types.ContinuousTestResult]): + The list of continuous test results. + 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 + + continuous_test_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ContinuousTestResult', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/experiment.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/experiment.py new file mode 100644 index 00000000..0cb3bbd1 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/experiment.py @@ -0,0 +1,570 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'Experiment', + 'VersionVariants', + 'VariantsHistory', + 'ListExperimentsRequest', + 'ListExperimentsResponse', + 'GetExperimentRequest', + 'CreateExperimentRequest', + 'UpdateExperimentRequest', + 'DeleteExperimentRequest', + 'StartExperimentRequest', + 'StopExperimentRequest', + }, +) + + +class Experiment(proto.Message): + r"""Represents an experiment in an environment. + Attributes: + name (str): + The name of the experiment. + Format: projects//locations//agents//environments//experiments/.. + display_name (str): + Required. The human-readable name of the + experiment (unique in an environment). Limit of + 64 characters. + description (str): + The human-readable description of the + experiment. + state (google.cloud.dialogflowcx_v3beta1.types.Experiment.State): + The current state of the experiment. + Transition triggered by + Expriments.StartExperiment: PENDING->RUNNING. + Transition triggered by + Expriments.CancelExperiment: PENDING->CANCELLED + or RUNNING->CANCELLED. + definition (google.cloud.dialogflowcx_v3beta1.types.Experiment.Definition): + The definition of the experiment. + result (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result): + Inference result of the experiment. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Creation time of this experiment. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of this experiment. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of this experiment. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Last update time of this experiment. + experiment_length (google.protobuf.duration_pb2.Duration): + Maximum number of days to run the experiment. + If auto-rollout is not enabled, default value + and maximum will be 30 days. If auto-rollout is + enabled, default value and maximum will be 6 + days. + variants_history (Sequence[google.cloud.dialogflowcx_v3beta1.types.VariantsHistory]): + The history of updates to the experiment + variants. + """ + class State(proto.Enum): + r"""The state of the experiment.""" + STATE_UNSPECIFIED = 0 + DRAFT = 1 + RUNNING = 2 + DONE = 3 + + class Definition(proto.Message): + r"""Definition of the experiment. + Attributes: + condition (str): + The condition defines which subset of sessions are selected + for this experiment. If not specified, all sessions are + eligible. E.g. "query_input.language_code=en" See the + `conditions + reference `__. + version_variants (google.cloud.dialogflowcx_v3beta1.types.VersionVariants): + The flow versions as the variants of this + experiment. + """ + + condition = proto.Field( + proto.STRING, + number=1, + ) + version_variants = proto.Field( + proto.MESSAGE, + number=2, + oneof='variants', + message='VersionVariants', + ) + + class Result(proto.Message): + r"""The inference result which includes an objective metric to + optimize and the confidence interval. + + Attributes: + version_metrics (Sequence[google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.VersionMetrics]): + Version variants and metrics. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + The last time the experiment's stats data was + updated. Will have default value if stats have + never been computed for this experiment. + """ + class MetricType(proto.Enum): + r"""Types of ratio-based metric for Dialogflow experiment.""" + METRIC_UNSPECIFIED = 0 + CONTAINED_SESSION_NO_CALLBACK_RATE = 1 + LIVE_AGENT_HANDOFF_RATE = 2 + CALLBACK_SESSION_RATE = 3 + ABANDONED_SESSION_RATE = 4 + SESSION_END_RATE = 5 + + class CountType(proto.Enum): + r"""types of count-based metric for Dialogflow experiment.""" + COUNT_TYPE_UNSPECIFIED = 0 + TOTAL_NO_MATCH_COUNT = 1 + TOTAL_TURN_COUNT = 2 + AVERAGE_TURN_COUNT = 3 + + class ConfidenceInterval(proto.Message): + r"""A confidence interval is a range of possible values for the + experiment objective you are trying to measure. + + Attributes: + confidence_level (float): + The confidence level used to construct the + interval, i.e. there is X% chance that the true + value is within this interval. + ratio (float): + The percent change between an experiment + metric's value and the value for its control. + lower_bound (float): + Lower bound of the interval. + upper_bound (float): + Upper bound of the interval. + """ + + confidence_level = proto.Field( + proto.DOUBLE, + number=1, + ) + ratio = proto.Field( + proto.DOUBLE, + number=2, + ) + lower_bound = proto.Field( + proto.DOUBLE, + number=3, + ) + upper_bound = proto.Field( + proto.DOUBLE, + number=4, + ) + + class Metric(proto.Message): + r"""Metric and corresponding confidence intervals. + Attributes: + type_ (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.MetricType): + Ratio-based metric type. Only one of type or count_type is + specified in each Metric. + count_type (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.CountType): + Count-based metric type. Only one of type or count_type is + specified in each Metric. + ratio (float): + Ratio value of a metric. + count (float): + Count value of a metric. + confidence_interval (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.ConfidenceInterval): + The probability that the treatment is better + than all other treatments in the experiment + """ + + type_ = proto.Field( + proto.ENUM, + number=1, + enum='Experiment.Result.MetricType', + ) + count_type = proto.Field( + proto.ENUM, + number=5, + enum='Experiment.Result.CountType', + ) + ratio = proto.Field( + proto.DOUBLE, + number=2, + oneof='value', + ) + count = proto.Field( + proto.DOUBLE, + number=4, + oneof='value', + ) + confidence_interval = proto.Field( + proto.MESSAGE, + number=3, + message='Experiment.Result.ConfidenceInterval', + ) + + class VersionMetrics(proto.Message): + r"""Version variant and associated metrics. + Attributes: + version (str): + The name of the flow + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + Format: + ``projects//locations//agents//flows//versions/``. + metrics (Sequence[google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.Metric]): + The metrics and corresponding confidence + intervals in the inference result. + session_count (int): + Number of sessions that were allocated to + this version. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + metrics = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Experiment.Result.Metric', + ) + session_count = proto.Field( + proto.INT32, + number=3, + ) + + version_metrics = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Experiment.Result.VersionMetrics', + ) + last_update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + definition = proto.Field( + proto.MESSAGE, + number=5, + message=Definition, + ) + result = proto.Field( + proto.MESSAGE, + number=6, + message=Result, + ) + create_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + start_time = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + end_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + last_update_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + experiment_length = proto.Field( + proto.MESSAGE, + number=11, + message=duration_pb2.Duration, + ) + variants_history = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='VariantsHistory', + ) + + +class VersionVariants(proto.Message): + r"""A list of flow version variants. + Attributes: + variants (Sequence[google.cloud.dialogflowcx_v3beta1.types.VersionVariants.Variant]): + A list of flow version variants. + """ + + class Variant(proto.Message): + r"""A single flow version with specified traffic allocation. + Attributes: + version (str): + The name of the flow version. Format: + ``projects//locations//agents//flows//versions/``. + traffic_allocation (float): + Percentage of the traffic which should be + routed to this version of flow. Traffic + allocation for a single flow must sum up to 1.0. + is_control_group (bool): + Whether the variant is for the control group. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + traffic_allocation = proto.Field( + proto.FLOAT, + number=2, + ) + is_control_group = proto.Field( + proto.BOOL, + number=3, + ) + + variants = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Variant, + ) + + +class VariantsHistory(proto.Message): + r"""The history of variants update. + Attributes: + version_variants (google.cloud.dialogflowcx_v3beta1.types.VersionVariants): + The flow versions as the variants. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Update time of the variants. + """ + + version_variants = proto.Field( + proto.MESSAGE, + number=1, + oneof='variants', + message='VersionVariants', + ) + update_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ListExperimentsRequest(proto.Message): + r"""The request message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + + Attributes: + parent (str): + Required. The + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to list all environments for. Format: + ``projects//locations//agents//environments/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 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 ListExperimentsResponse(proto.Message): + r"""The response message for + [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. + + Attributes: + experiments (Sequence[google.cloud.dialogflowcx_v3beta1.types.Experiment]): + The list of experiments. There will be a maximum number of + items returned based on the page_size field in the request. + The list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + 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 + + experiments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Experiment', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetExperimentRequest(proto.Message): + r"""The request message for + [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.GetExperiment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateExperimentRequest(proto.Message): + r"""The request message for + [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.CreateExperiment]. + + Attributes: + parent (str): + Required. The + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to create + an + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + for. Format: + ``projects//locations//agents//environments/``. + experiment (google.cloud.dialogflowcx_v3beta1.types.Experiment): + Required. The experiment to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + experiment = proto.Field( + proto.MESSAGE, + number=2, + message='Experiment', + ) + + +class UpdateExperimentRequest(proto.Message): + r"""The request message for + [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.UpdateExperiment]. + + Attributes: + experiment (google.cloud.dialogflowcx_v3beta1.types.Experiment): + Required. The experiment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + experiment = proto.Field( + proto.MESSAGE, + number=1, + message='Experiment', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteExperimentRequest(proto.Message): + r"""The request message for + [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.DeleteExperiment]. + + Attributes: + name (str): + Required. The name of the + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + to delete. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class StartExperimentRequest(proto.Message): + r"""The request message for + [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StartExperiment]. + + Attributes: + name (str): + Required. Resource name of the experiment to start. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class StopExperimentRequest(proto.Message): + r"""The request message for + [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StopExperiment]. + + Attributes: + name (str): + Required. Resource name of the experiment to stop. Format: + ``projects//locations//agents//environments//experiments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/flow.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/flow.py new file mode 100644 index 00000000..46cd9a9c --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/flow.py @@ -0,0 +1,640 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import validation_message +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'NluSettings', + 'Flow', + 'CreateFlowRequest', + 'DeleteFlowRequest', + 'ListFlowsRequest', + 'ListFlowsResponse', + 'GetFlowRequest', + 'UpdateFlowRequest', + 'TrainFlowRequest', + 'ValidateFlowRequest', + 'GetFlowValidationResultRequest', + 'FlowValidationResult', + 'ImportFlowRequest', + 'ImportFlowResponse', + 'ExportFlowRequest', + 'ExportFlowResponse', + }, +) + + +class NluSettings(proto.Message): + r"""Settings related to NLU. + Attributes: + model_type (google.cloud.dialogflowcx_v3beta1.types.NluSettings.ModelType): + Indicates the type of NLU model. + classification_threshold (float): + 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 no-match event 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. + model_training_mode (google.cloud.dialogflowcx_v3beta1.types.NluSettings.ModelTrainingMode): + Indicates NLU model training mode. + """ + class ModelType(proto.Enum): + r"""NLU model type.""" + MODEL_TYPE_UNSPECIFIED = 0 + MODEL_TYPE_STANDARD = 1 + MODEL_TYPE_ADVANCED = 3 + + class ModelTrainingMode(proto.Enum): + r"""NLU model training mode.""" + MODEL_TRAINING_MODE_UNSPECIFIED = 0 + MODEL_TRAINING_MODE_AUTOMATIC = 1 + MODEL_TRAINING_MODE_MANUAL = 2 + + model_type = proto.Field( + proto.ENUM, + number=1, + enum=ModelType, + ) + classification_threshold = proto.Field( + proto.FLOAT, + number=3, + ) + model_training_mode = proto.Field( + proto.ENUM, + number=4, + enum=ModelTrainingMode, + ) + + +class Flow(proto.Message): + r"""Flows represents the conversation flows when you build your + chatbot agent. + A flow consists of many pages connected by the transition + routes. Conversations always start with the built-in Start Flow + (with an all-0 ID). Transition routes can direct the + conversation session from the current flow (parent flow) to + another flow (sub flow). When the sub flow is finished, + Dialogflow will bring the session back to the parent flow, where + the sub flow is started. + + Usually, when a transition route is followed by a matched + intent, the intent will be "consumed". This means the intent + won't activate more transition routes. However, when the + followed transition route moves the conversation session into a + different flow, the matched intent can be carried over and to be + consumed in the target flow. + + Attributes: + name (str): + The unique identifier of the flow. Format: + ``projects//locations//agents//flows/``. + display_name (str): + Required. The human-readable name of the + flow. + description (str): + The description of the flow. The maximum + length is 500 characters. If exceeded, the + request is rejected. + transition_routes (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRoute]): + A flow's transition routes serve two purposes: + + - They are responsible for matching the user's first + utterances in the flow. + - They are inherited by every page's [transition + routes][Page.transition_routes] and can support use cases + such as the user saying "help" or "can I talk to a + human?", which can be handled in a common way regardless + of the current page. Transition routes defined in the + page have higher priority than those defined in the flow. + + TransitionRoutes are evalauted in the following order: + + - TransitionRoutes with intent specified.. + - TransitionRoutes with only condition specified. + + TransitionRoutes with intent specified are inherited by + pages in the flow. + event_handlers (Sequence[google.cloud.dialogflowcx_v3beta1.types.EventHandler]): + A flow's event handlers serve two purposes: + + - They are responsible for handling events (e.g. no match, + webhook errors) in the flow. + - They are inherited by every page's [event + handlers][Page.event_handlers], which can be used to + handle common events regardless of the current page. + Event handlers defined in the page have higher priority + than those defined in the flow. + + Unlike + [transition_routes][google.cloud.dialogflow.cx.v3beta1.Flow.transition_routes], + these handlers are evaluated on a first-match basis. The + first one that matches the event get executed, with the rest + being ignored. + transition_route_groups (Sequence[str]): + A flow's transition route group serve two purposes: + + - They are responsible for matching the user's first + utterances in the flow. + - They are inherited by every page's [transition route + groups][Page.transition_route_groups]. Transition route + groups defined in the page have higher priority than + those defined in the flow. + + Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. + nlu_settings (google.cloud.dialogflowcx_v3beta1.types.NluSettings): + NLU related settings of the flow. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + transition_routes = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=page.TransitionRoute, + ) + event_handlers = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=page.EventHandler, + ) + transition_route_groups = proto.RepeatedField( + proto.STRING, + number=15, + ) + nlu_settings = proto.Field( + proto.MESSAGE, + number=11, + message='NluSettings', + ) + + +class CreateFlowRequest(proto.Message): + r"""The request message for + [Flows.CreateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.CreateFlow]. + + Attributes: + parent (str): + Required. The agent to create a flow for. Format: + ``projects//locations//agents/``. + flow (google.cloud.dialogflowcx_v3beta1.types.Flow): + Required. The flow to create. + language_code (str): + The language of the following fields in ``flow``: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + flow = proto.Field( + proto.MESSAGE, + number=2, + message='Flow', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteFlowRequest(proto.Message): + r"""The request message for + [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3beta1.Flows.DeleteFlow]. + + Attributes: + name (str): + Required. The name of the flow to delete. Format: + ``projects//locations//agents//flows/``. + force (bool): + This field has no effect for flows with no incoming + transitions. For flows with incoming transitions: + + - If ``force`` is set to false, an error will be returned + with message indicating the incoming transitions. + - If ``force`` is set to true, Dialogflow will remove the + flow, as well as any transitions to the flow (i.e. + [Target flow][EventHandler.target_flow] in event handlers + or [Target flow][TransitionRoute.target_flow] in + transition routes that point to this flow will be + cleared). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class ListFlowsRequest(proto.Message): + r"""The request message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. + + Attributes: + parent (str): + Required. The agent containing the flows. Format: + ``projects//locations//agents/``. + 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. + language_code (str): + The language to list flows for. The following fields are + language dependent: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class ListFlowsResponse(proto.Message): + r"""The response message for + [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. + + Attributes: + flows (Sequence[google.cloud.dialogflowcx_v3beta1.types.Flow]): + The list of flows. 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 + + flows = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Flow', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFlowRequest(proto.Message): + r"""The response message for + [Flows.GetFlow][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlow]. + + Attributes: + name (str): + Required. The name of the flow to get. Format: + ``projects//locations//agents//flows/``. + language_code (str): + The language to retrieve the flow for. The following fields + are language dependent: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateFlowRequest(proto.Message): + r"""The request message for + [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.UpdateFlow]. + + Attributes: + flow (google.cloud.dialogflowcx_v3beta1.types.Flow): + Required. The flow to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields get updated. If + ``update_mask`` is not specified, an error will be returned. + language_code (str): + The language of the following fields in ``flow``: + + - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + flow = proto.Field( + proto.MESSAGE, + number=1, + message='Flow', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class TrainFlowRequest(proto.Message): + r"""The request message for + [Flows.TrainFlow][google.cloud.dialogflow.cx.v3beta1.Flows.TrainFlow]. + + Attributes: + name (str): + Required. The flow to train. Format: + ``projects//locations//agents//flows/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class ValidateFlowRequest(proto.Message): + r"""The request message for + [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ValidateFlow]. + + Attributes: + name (str): + Required. The flow to validate. Format: + ``projects//locations//agents//flows/``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFlowValidationResultRequest(proto.Message): + r"""The request message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. + + Attributes: + name (str): + Required. The flow name. Format: + ``projects//locations//agents//flows//validationResult``. + language_code (str): + If not specified, the agent's default + language is used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class FlowValidationResult(proto.Message): + r"""The response message for + [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. + + Attributes: + name (str): + The unique identifier of the flow validation result. Format: + ``projects//locations//agents//flows//validationResult``. + validation_messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ValidationMessage]): + Contains all validation messages. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Last time the flow was validated. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + validation_messages = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=validation_message.ValidationMessage, + ) + update_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class ImportFlowRequest(proto.Message): + r"""The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + + Attributes: + parent (str): + Required. The agent to import the flow into. Format: + ``projects//locations//agents/``. + flow_uri (str): + The `Google Cloud + Storage `__ URI to + import flow from. The format of this URI must be + ``gs:///``. + flow_content (bytes): + Uncompressed raw byte content for flow. + import_option (google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest.ImportOption): + Flow import mode. If not specified, ``KEEP`` is assumed. + """ + class ImportOption(proto.Enum): + r"""Import option.""" + IMPORT_OPTION_UNSPECIFIED = 0 + KEEP = 1 + FALLBACK = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + flow_uri = proto.Field( + proto.STRING, + number=2, + oneof='flow', + ) + flow_content = proto.Field( + proto.BYTES, + number=3, + oneof='flow', + ) + import_option = proto.Field( + proto.ENUM, + number=4, + enum=ImportOption, + ) + + +class ImportFlowResponse(proto.Message): + r"""The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + + Attributes: + flow (str): + The unique identifier of the new flow. Format: + ``projects//locations//agents//flows/``. + """ + + flow = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportFlowRequest(proto.Message): + r"""The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + + Attributes: + name (str): + Required. The name of the flow to export. Format: + ``projects//locations//agents//flows/``. + flow_uri (str): + Optional. The `Google Cloud + Storage `__ URI to + export the flow to. The format of this URI must be + ``gs:///``. If left unspecified, + the serialized flow is returned inline. + include_referenced_flows (bool): + Optional. Whether to export flows referenced + by the specified flow. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + flow_uri = proto.Field( + proto.STRING, + number=2, + ) + include_referenced_flows = proto.Field( + proto.BOOL, + number=4, + ) + + +class ExportFlowResponse(proto.Message): + r"""The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + + Attributes: + flow_uri (str): + The URI to a file containing the exported flow. This field + is populated only if ``flow_uri`` is specified in + [ExportFlowRequest][google.cloud.dialogflow.cx.v3beta1.ExportFlowRequest]. + flow_content (bytes): + Uncompressed raw byte content for flow. + """ + + flow_uri = proto.Field( + proto.STRING, + number=1, + oneof='flow', + ) + flow_content = proto.Field( + proto.BYTES, + number=2, + oneof='flow', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py new file mode 100644 index 00000000..ca030695 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import response_message +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'Fulfillment', + }, +) + + +class Fulfillment(proto.Message): + r"""A fulfillment can do one or more of the following actions at the + same time: + + - Generate rich message responses. + - Set parameter values. + - Call the webhook. + + Fulfillments can be called at various stages in the + [Page][google.cloud.dialogflow.cx.v3beta1.Page] or + [Form][google.cloud.dialogflow.cx.v3beta1.Form] lifecycle. For + example, when a + [DetectIntentRequest][google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest] + drives a session to enter a new page, the page's entry fulfillment + can add a static response to the + [QueryResult][google.cloud.dialogflow.cx.v3beta1.QueryResult] in the + returning + [DetectIntentResponse][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse], + call the webhook (for example, to load user data from a database), + or both. + + Attributes: + messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage]): + The list of rich message responses to present + to the user. + webhook (str): + The webhook to call. Format: + ``projects//locations//agents//webhooks/``. + tag (str): + The tag used by the webhook to identify which fulfillment is + being called. This field is required if ``webhook`` is + specified. + set_parameter_actions (Sequence[google.cloud.dialogflowcx_v3beta1.types.Fulfillment.SetParameterAction]): + Set parameter values before executing the + webhook. + conditional_cases (Sequence[google.cloud.dialogflowcx_v3beta1.types.Fulfillment.ConditionalCases]): + Conditional cases for this fulfillment. + """ + + class SetParameterAction(proto.Message): + r"""Setting a parameter value. + Attributes: + parameter (str): + Display name of the parameter. + value (google.protobuf.struct_pb2.Value): + The new value of the parameter. A null value + clears the parameter. + """ + + parameter = proto.Field( + proto.STRING, + number=1, + ) + value = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + class ConditionalCases(proto.Message): + r"""A list of cascading if-else conditions. Cases are mutually + exclusive. The first one with a matching condition is selected, + all the rest ignored. + + Attributes: + cases (Sequence[google.cloud.dialogflowcx_v3beta1.types.Fulfillment.ConditionalCases.Case]): + A list of cascading if-else conditions. + """ + + class Case(proto.Message): + r"""Each case has a Boolean condition. When it is evaluated to be + True, the corresponding messages will be selected and evaluated + recursively. + + Attributes: + condition (str): + The condition to activate and select this case. Empty means + the condition is always true. The condition is evaluated + against [form parameters][Form.parameters] or [session + parameters][SessionInfo.parameters]. + + See the `conditions + reference `__. + case_content (Sequence[google.cloud.dialogflowcx_v3beta1.types.Fulfillment.ConditionalCases.Case.CaseContent]): + A list of case content. + """ + + class CaseContent(proto.Message): + r"""The list of messages or conditional cases to activate for + this case. + + Attributes: + message (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage): + Returned message. + additional_cases (google.cloud.dialogflowcx_v3beta1.types.Fulfillment.ConditionalCases): + Additional cases to be evaluated. + """ + + message = proto.Field( + proto.MESSAGE, + number=1, + oneof='cases_or_message', + message=response_message.ResponseMessage, + ) + additional_cases = proto.Field( + proto.MESSAGE, + number=2, + oneof='cases_or_message', + message='Fulfillment.ConditionalCases', + ) + + condition = proto.Field( + proto.STRING, + number=1, + ) + case_content = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Fulfillment.ConditionalCases.Case.CaseContent', + ) + + cases = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Fulfillment.ConditionalCases.Case', + ) + + messages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=response_message.ResponseMessage, + ) + webhook = proto.Field( + proto.STRING, + number=2, + ) + tag = proto.Field( + proto.STRING, + number=3, + ) + set_parameter_actions = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=SetParameterAction, + ) + conditional_cases = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=ConditionalCases, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/intent.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/intent.py new file mode 100644 index 00000000..656933f6 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/intent.py @@ -0,0 +1,474 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cx.v3beta1', + manifest={ + 'IntentView', + 'Intent', + 'ListIntentsRequest', + 'ListIntentsResponse', + 'GetIntentRequest', + 'CreateIntentRequest', + 'UpdateIntentRequest', + 'DeleteIntentRequest', + }, +) + + +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. + """ + INTENT_VIEW_UNSPECIFIED = 0 + INTENT_VIEW_PARTIAL = 1 + INTENT_VIEW_FULL = 2 + + +class Intent(proto.Message): + r"""An intent represents a user's intent to interact with a + conversational agent. + You can provide information for the Dialogflow API to use to + match user input to an intent by adding training phrases (i.e., + examples of user input) to your intent. + + Attributes: + name (str): + The unique identifier of the intent. Required for the + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.UpdateIntent] + method. + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.CreateIntent] + populates the name automatically. Format: + ``projects//locations//agents//intents/``. + display_name (str): + Required. The human-readable name of the + intent, unique within the agent. + training_phrases (Sequence[google.cloud.dialogflowcx_v3beta1.types.Intent.TrainingPhrase]): + The collection of training phrases the agent + is trained on to identify the intent. + parameters (Sequence[google.cloud.dialogflowcx_v3beta1.types.Intent.Parameter]): + The collection of parameters associated with + the intent. + priority (int): + 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): + Indicates whether this is a fallback intent. + Currently only default fallback intent is + allowed in the agent, which is added upon agent + creation. + Adding training phrases to fallback intent is + useful in the case of requests that are + mistakenly matched, since training phrases + assigned to fallback intents act as negative + examples that triggers no-match event. + labels (Sequence[google.cloud.dialogflowcx_v3beta1.types.Intent.LabelsEntry]): + The key/value metadata to label an intent. Labels can + contain lowercase letters, digits and the symbols '-' and + '_'. International characters are allowed, including letters + from unicase alphabets. Keys must start with a letter. Keys + and values can be no longer than 63 characters and no more + than 128 bytes. + + Prefix "sys-" is reserved for Dialogflow defined labels. + Currently allowed Dialogflow defined labels include: + + - sys-head + - sys-contextual The above labels do not require value. + "sys-head" means the intent is a head intent. + "sys-contextual" means the intent is a contextual intent. + description (str): + Human readable description for better + understanding an intent like its scope, content, + result etc. Maximum character limit: 140 + characters. + """ + + class TrainingPhrase(proto.Message): + r"""Represents an example that the agent is trained on to + identify the intent. + + Attributes: + id (str): + Output only. The unique identifier of the + training phrase. + parts (Sequence[google.cloud.dialogflowcx_v3beta1.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.cx.v3beta1.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 ``parameter_id`` field is set. + repeat_count (int): + Indicates how many times this example was + added to the intent. + """ + + class Part(proto.Message): + r"""Represents a part of a training phrase. + Attributes: + text (str): + Required. The text for this part. + parameter_id (str): + The + [parameter][google.cloud.dialogflow.cx.v3beta1.Intent.Parameter] + used to annotate this part of the training phrase. This + field is required for annotated parts of the training + phrase. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + parameter_id = proto.Field( + proto.STRING, + number=2, + ) + + id = proto.Field( + proto.STRING, + number=1, + ) + parts = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Intent.TrainingPhrase.Part', + ) + repeat_count = proto.Field( + proto.INT32, + number=3, + ) + + class Parameter(proto.Message): + r"""Represents an intent parameter. + Attributes: + id (str): + Required. The unique identifier of the parameter. This field + is used by [training + phrases][google.cloud.dialogflow.cx.v3beta1.Intent.TrainingPhrase] + to annotate their + [parts][google.cloud.dialogflow.cx.v3beta1.Intent.TrainingPhrase.Part]. + entity_type (str): + Required. The entity type of the parameter. Format: + ``projects/-/locations/-/agents/-/entityTypes/`` + for system entity types (for example, + ``projects/-/locations/-/agents/-/entityTypes/sys.date``), + or + ``projects//locations//agents//entityTypes/`` + for developer entity types. + is_list (bool): + Indicates whether the parameter represents a + list of values. + redact (bool): + Indicates whether the parameter content should be redacted + in log. If redaction is enabled, the parameter content will + be replaced by parameter name during logging. Note: the + parameter content is subject to redaction if either + parameter level redaction or [entity type level + redaction][google.cloud.dialogflow.cx.v3beta1.EntityType.redact] + is enabled. + """ + + id = proto.Field( + proto.STRING, + number=1, + ) + entity_type = proto.Field( + proto.STRING, + number=2, + ) + is_list = proto.Field( + proto.BOOL, + number=3, + ) + redact = proto.Field( + proto.BOOL, + number=4, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + training_phrases = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TrainingPhrase, + ) + parameters = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Parameter, + ) + priority = proto.Field( + proto.INT32, + number=5, + ) + is_fallback = proto.Field( + proto.BOOL, + number=6, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + description = proto.Field( + proto.STRING, + number=8, + ) + + +class ListIntentsRequest(proto.Message): + r"""The request message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.Intents.ListIntents]. + + Attributes: + parent (str): + Required. The agent to list all intents for. Format: + ``projects//locations//agents/``. + language_code (str): + The language to list intents for. The following fields are + language dependent: + + - ``Intent.training_phrases.parts.text`` + + 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. + intent_view (google.cloud.dialogflowcx_v3beta1.types.IntentView): + The resource view to apply to the returned + intent. + 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, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + intent_view = proto.Field( + proto.ENUM, + number=5, + enum='IntentView', + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListIntentsResponse(proto.Message): + r"""The response message for + [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.Intents.ListIntents]. + + Attributes: + intents (Sequence[google.cloud.dialogflowcx_v3beta1.types.Intent]): + The list of 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.cx.v3beta1.Intents.GetIntent]. + + Attributes: + name (str): + Required. The name of the intent. Format: + ``projects//locations//agents//intents/``. + language_code (str): + The language to retrieve the intent for. The following + fields are language dependent: + + - ``Intent.training_phrases.parts.text`` + + 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. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateIntentRequest(proto.Message): + r"""The request message for + [Intents.CreateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.CreateIntent]. + + Attributes: + parent (str): + Required. The agent to create an intent for. Format: + ``projects//locations//agents/``. + intent (google.cloud.dialogflowcx_v3beta1.types.Intent): + Required. The intent to create. + language_code (str): + The language of the following fields in ``intent``: + + - ``Intent.training_phrases.parts.text`` + + 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, + ) + intent = proto.Field( + proto.MESSAGE, + number=2, + message='Intent', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateIntentRequest(proto.Message): + r"""The request message for + [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.UpdateIntent]. + + Attributes: + intent (google.cloud.dialogflowcx_v3beta1.types.Intent): + Required. The intent to update. + language_code (str): + The language of the following fields in ``intent``: + + - ``Intent.training_phrases.parts.text`` + + 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. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + updated. + """ + + 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, + ) + + +class DeleteIntentRequest(proto.Message): + r"""The request message for + [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3beta1.Intents.DeleteIntent]. + + Attributes: + name (str): + Required. The name of the intent to delete. Format: + ``projects//locations//agents//intents/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/page.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/page.py new file mode 100644 index 00000000..aff9f8da --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/page.py @@ -0,0 +1,730 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'Page', + 'Form', + 'EventHandler', + 'TransitionRoute', + 'ListPagesRequest', + 'ListPagesResponse', + 'GetPageRequest', + 'CreatePageRequest', + 'UpdatePageRequest', + 'DeletePageRequest', + }, +) + + +class Page(proto.Message): + r"""A Dialogflow CX conversation (session) can be described and + visualized as a state machine. The states of a CX session are + represented by pages. + + For each flow, you define many pages, where your combined pages can + handle a complete conversation on the topics the flow is designed + for. At any given moment, exactly one page is the current page, the + current page is considered active, and the flow associated with that + page is considered active. Every flow has a special start page. When + a flow initially becomes active, the start page page becomes the + current page. For each conversational turn, the current page will + either stay the same or transition to another page. + + You configure each page to collect information from the end-user + that is relevant for the conversational state represented by the + page. + + For more information, see the `Page + guide `__. + + Attributes: + name (str): + The unique identifier of the page. Required for the + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3beta1.Pages.UpdatePage] + method. + [Pages.CreatePage][google.cloud.dialogflow.cx.v3beta1.Pages.CreatePage] + populates the name automatically. Format: + ``projects//locations//agents//flows//pages/``. + display_name (str): + Required. The human-readable name of the + page, unique within the agent. + entry_fulfillment (google.cloud.dialogflowcx_v3beta1.types.Fulfillment): + The fulfillment to call when the session is + entering the page. + form (google.cloud.dialogflowcx_v3beta1.types.Form): + The form associated with the page, used for + collecting parameters relevant to the page. + transition_route_groups (Sequence[str]): + Ordered list of + [``TransitionRouteGroups``][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + associated with the page. Transition route groups must be + unique within a page. + + - If multiple transition routes within a page scope refer + to the same intent, then the precedence order is: page's + transition route -> page's transition route group -> + flow's transition routes. + + - If multiple transition route groups within a page contain + the same intent, then the first group in the ordered list + takes precedence. + + Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. + transition_routes (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRoute]): + A list of transitions for the transition rules of this page. + They route the conversation to another page in the same + flow, or another flow. + + When we are in a certain page, the TransitionRoutes are + evalauted in the following order: + + - TransitionRoutes defined in the page with intent + specified. + - TransitionRoutes defined in the [transition route + groups][google.cloud.dialogflow.cx.v3beta1.Page.transition_route_groups] + with intent specified. + - TransitionRoutes defined in flow with intent specified. + - TransitionRoutes defined in the [transition route + groups][google.cloud.dialogflow.cx.v3beta1.Flow.transition_route_groups] + with intent specified. + - TransitionRoutes defined in the page with only condition + specified. + - TransitionRoutes defined in the [transition route + groups][google.cloud.dialogflow.cx.v3beta1.Page.transition_route_groups] + with only condition specified. + event_handlers (Sequence[google.cloud.dialogflowcx_v3beta1.types.EventHandler]): + Handlers associated with the page to handle + events such as webhook errors, no match or no + input. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + entry_fulfillment = proto.Field( + proto.MESSAGE, + number=7, + message=fulfillment.Fulfillment, + ) + form = proto.Field( + proto.MESSAGE, + number=4, + message='Form', + ) + transition_route_groups = proto.RepeatedField( + proto.STRING, + number=11, + ) + transition_routes = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='TransitionRoute', + ) + event_handlers = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='EventHandler', + ) + + +class Form(proto.Message): + r"""A form is a data model that groups related parameters that can be + collected from the user. The process in which the agent prompts the + user and collects parameter values from the user is called form + filling. A form can be added to a + [page][google.cloud.dialogflow.cx.v3beta1.Page]. When form filling + is done, the filled parameters will be written to the + [session][google.cloud.dialogflow.cx.v3beta1.SessionInfo.parameters]. + + Attributes: + parameters (Sequence[google.cloud.dialogflowcx_v3beta1.types.Form.Parameter]): + Parameters to collect from the user. + """ + + class Parameter(proto.Message): + r"""Represents a form parameter. + Attributes: + display_name (str): + Required. The human-readable name of the + parameter, unique within the form. + required (bool): + Indicates whether the parameter is required. + Optional parameters will not trigger prompts; + however, they are filled if the user specifies + them. Required parameters must be filled before + form filling concludes. + entity_type (str): + Required. The entity type of the parameter. Format: + ``projects/-/locations/-/agents/-/entityTypes/`` + for system entity types (for example, + ``projects/-/locations/-/agents/-/entityTypes/sys.date``), + or + ``projects//locations//agents//entityTypes/`` + for developer entity types. + is_list (bool): + Indicates whether the parameter represents a + list of values. + fill_behavior (google.cloud.dialogflowcx_v3beta1.types.Form.Parameter.FillBehavior): + Required. Defines fill behavior for the + parameter. + default_value (google.protobuf.struct_pb2.Value): + The default value of an optional parameter. + If the parameter is required, the default value + will be ignored. + redact (bool): + Indicates whether the parameter content should be redacted + in log. If redaction is enabled, the parameter content will + be replaced by parameter name during logging. Note: the + parameter content is subject to redaction if either + parameter level redaction or [entity type level + redaction][google.cloud.dialogflow.cx.v3beta1.EntityType.redact] + is enabled. + """ + + class FillBehavior(proto.Message): + r"""Configuration for how the filling of a parameter should be + handled. + + Attributes: + initial_prompt_fulfillment (google.cloud.dialogflowcx_v3beta1.types.Fulfillment): + Required. The fulfillment to provide the + initial prompt that the agent can present to the + user in order to fill the parameter. + reprompt_event_handlers (Sequence[google.cloud.dialogflowcx_v3beta1.types.EventHandler]): + The handlers for parameter-level events, used to provide + reprompt for the parameter or transition to a different + page/flow. The supported events are: + + - ``sys.no-match-``, where N can be from 1 to 6 + - ``sys.no-match-default`` + - ``sys.no-input-``, where N can be from 1 to 6 + - ``sys.no-input-default`` + - ``sys.invalid-parameter`` + + ``initial_prompt_fulfillment`` provides the first prompt for + the parameter. + + If the user's response does not fill the parameter, a + no-match/no-input event will be triggered, and the + fulfillment associated with the + ``sys.no-match-1``/``sys.no-input-1`` handler (if defined) + will be called to provide a prompt. The + ``sys.no-match-2``/``sys.no-input-2`` handler (if defined) + will respond to the next no-match/no-input event, and so on. + + A ``sys.no-match-default`` or ``sys.no-input-default`` + handler will be used to handle all following + no-match/no-input events after all numbered + no-match/no-input handlers for the parameter are consumed. + + A ``sys.invalid-parameter`` handler can be defined to handle + the case where the parameter values have been + ``invalidated`` by webhook. For example, if the user's + response fill the parameter, however the parameter was + invalidated by webhook, the fulfillment associated with the + ``sys.invalid-parameter`` handler (if defined) will be + called to provide a prompt. + + If the event handler for the corresponding event can't be + found on the parameter, ``initial_prompt_fulfillment`` will + be re-prompted. + """ + + initial_prompt_fulfillment = proto.Field( + proto.MESSAGE, + number=3, + message=fulfillment.Fulfillment, + ) + reprompt_event_handlers = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='EventHandler', + ) + + display_name = proto.Field( + proto.STRING, + number=1, + ) + required = proto.Field( + proto.BOOL, + number=2, + ) + entity_type = proto.Field( + proto.STRING, + number=3, + ) + is_list = proto.Field( + proto.BOOL, + number=4, + ) + fill_behavior = proto.Field( + proto.MESSAGE, + number=7, + message='Form.Parameter.FillBehavior', + ) + default_value = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Value, + ) + redact = proto.Field( + proto.BOOL, + number=11, + ) + + parameters = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Parameter, + ) + + +class EventHandler(proto.Message): + r"""An event handler specifies an + [event][google.cloud.dialogflow.cx.v3beta1.EventHandler.event] that + can be handled during a session. When the specified event happens, + the following actions are taken in order: + + - If there is a + [``trigger_fulfillment``][google.cloud.dialogflow.cx.v3beta1.EventHandler.trigger_fulfillment] + associated with the event, it will be called. + - If there is a + [``target_page``][google.cloud.dialogflow.cx.v3beta1.EventHandler.target_page] + associated with the event, the session will transition into the + specified page. + - If there is a + [``target_flow``][google.cloud.dialogflow.cx.v3beta1.EventHandler.target_flow] + associated with the event, the session will transition into the + specified flow. + + Attributes: + name (str): + Output only. The unique identifier of this + event handler. + event (str): + Required. The name of the event to handle. + trigger_fulfillment (google.cloud.dialogflowcx_v3beta1.types.Fulfillment): + The fulfillment to call when the event + occurs. Handling webhook errors with a + fulfillment enabled with webhook could cause + infinite loop. It is invalid to specify such + fulfillment for a handler handling webhooks. + target_page (str): + The target page to transition to. Format: + ``projects//locations//agents//flows//pages/``. + target_flow (str): + The target flow to transition to. Format: + ``projects//locations//agents//flows/``. + """ + + name = proto.Field( + proto.STRING, + number=6, + ) + event = proto.Field( + proto.STRING, + number=4, + ) + trigger_fulfillment = proto.Field( + proto.MESSAGE, + number=5, + message=fulfillment.Fulfillment, + ) + target_page = proto.Field( + proto.STRING, + number=2, + oneof='target', + ) + target_flow = proto.Field( + proto.STRING, + number=3, + oneof='target', + ) + + +class TransitionRoute(proto.Message): + r"""A transition route specifies a + [intent][google.cloud.dialogflow.cx.v3beta1.Intent] that can be + matched and/or a data condition that can be evaluated during a + session. When a specified transition is matched, the following + actions are taken in order: + + - If there is a + [``trigger_fulfillment``][google.cloud.dialogflow.cx.v3beta1.TransitionRoute.trigger_fulfillment] + associated with the transition, it will be called. + - If there is a + [``target_page``][google.cloud.dialogflow.cx.v3beta1.TransitionRoute.target_page] + associated with the transition, the session will transition into + the specified page. + - If there is a + [``target_flow``][google.cloud.dialogflow.cx.v3beta1.TransitionRoute.target_flow] + associated with the transition, the session will transition into + the specified flow. + + Attributes: + name (str): + Output only. The unique identifier of this + transition route. + intent (str): + The unique identifier of an + [Intent][google.cloud.dialogflow.cx.v3beta1.Intent]. Format: + ``projects//locations//agents//intents/``. + Indicates that the transition can only happen when the given + intent is matched. At least one of ``intent`` or + ``condition`` must be specified. When both ``intent`` and + ``condition`` are specified, the transition can only happen + when both are fulfilled. + condition (str): + The condition to evaluate against [form + parameters][google.cloud.dialogflow.cx.v3beta1.Form.parameters] + or [session + parameters][google.cloud.dialogflow.cx.v3beta1.SessionInfo.parameters]. + + See the `conditions + reference `__. + At least one of ``intent`` or ``condition`` must be + specified. When both ``intent`` and ``condition`` are + specified, the transition can only happen when both are + fulfilled. + trigger_fulfillment (google.cloud.dialogflowcx_v3beta1.types.Fulfillment): + The fulfillment to call when the condition is satisfied. At + least one of ``trigger_fulfillment`` and ``target`` must be + specified. When both are defined, ``trigger_fulfillment`` is + executed first. + target_page (str): + The target page to transition to. Format: + ``projects//locations//agents//flows//pages/``. + target_flow (str): + The target flow to transition to. Format: + ``projects//locations//agents//flows/``. + """ + + name = proto.Field( + proto.STRING, + number=6, + ) + intent = proto.Field( + proto.STRING, + number=1, + ) + condition = proto.Field( + proto.STRING, + number=2, + ) + trigger_fulfillment = proto.Field( + proto.MESSAGE, + number=3, + message=fulfillment.Fulfillment, + ) + target_page = proto.Field( + proto.STRING, + number=4, + oneof='target', + ) + target_flow = proto.Field( + proto.STRING, + number=5, + oneof='target', + ) + + +class ListPagesRequest(proto.Message): + r"""The request message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. + + Attributes: + parent (str): + Required. The flow to list all pages for. Format: + ``projects//locations//agents//flows/``. + language_code (str): + The language to list pages for. The following fields are + language dependent: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + 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, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class ListPagesResponse(proto.Message): + r"""The response message for + [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. + + Attributes: + pages (Sequence[google.cloud.dialogflowcx_v3beta1.types.Page]): + The list of pages. 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 + + pages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Page', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetPageRequest(proto.Message): + r"""The request message for + [Pages.GetPage][google.cloud.dialogflow.cx.v3beta1.Pages.GetPage]. + + Attributes: + name (str): + Required. The name of the page. Format: + ``projects//locations//agents//flows//pages/``. + language_code (str): + The language to retrieve the page for. The following fields + are language dependent: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreatePageRequest(proto.Message): + r"""The request message for + [Pages.CreatePage][google.cloud.dialogflow.cx.v3beta1.Pages.CreatePage]. + + Attributes: + parent (str): + Required. The flow to create a page for. Format: + ``projects//locations//agents//flows/``. + page (google.cloud.dialogflowcx_v3beta1.types.Page): + Required. The page to create. + language_code (str): + The language of the following fields in ``page``: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page = proto.Field( + proto.MESSAGE, + number=2, + message='Page', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdatePageRequest(proto.Message): + r"""The request message for + [Pages.UpdatePage][google.cloud.dialogflow.cx.v3beta1.Pages.UpdatePage]. + + Attributes: + page (google.cloud.dialogflowcx_v3beta1.types.Page): + Required. The page to update. + language_code (str): + The language of the following fields in ``page``: + + - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` + - + + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + updated. + """ + + page = proto.Field( + proto.MESSAGE, + number=1, + message='Page', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeletePageRequest(proto.Message): + r"""The request message for + [Pages.DeletePage][google.cloud.dialogflow.cx.v3beta1.Pages.DeletePage]. + + Attributes: + name (str): + Required. The name of the page to delete. Format: + ``projects//locations//agents//Flows//pages/``. + force (bool): + This field has no effect for pages with no incoming + transitions. For pages with incoming transitions: + + - If ``force`` is set to false, an error will be returned + with message indicating the incoming transitions. + - If ``force`` is set to true, Dialogflow will remove the + page, as well as any transitions to the page (i.e. + [Target page][EventHandler.target_page] in event handlers + or [Target page][TransitionRoute.target_page] in + transition routes that point to this page will be + cleared). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/response_message.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/response_message.py new file mode 100644 index 00000000..981918e8 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/response_message.py @@ -0,0 +1,340 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'ResponseMessage', + }, +) + + +class ResponseMessage(proto.Message): + r"""Represents a response message that can be returned by a + conversational agent. + + Response messages are also used for output audio synthesis. The + approach is as follows: + + - If at least one OutputAudioText response is present, then all + OutputAudioText responses are linearly concatenated, and the + result is used for output audio synthesis. + - If the OutputAudioText responses are a mixture of text and SSML, + then the concatenated result is treated as SSML; otherwise, the + result is treated as either text or SSML as appropriate. The + agent designer should ideally use either text or SSML + consistently throughout the bot design. + - Otherwise, all Text responses are linearly concatenated, and the + result is used for output audio synthesis. + + This approach allows for more sophisticated user experience + scenarios, where the text displayed to the user may differ from what + is heard. + + Attributes: + text (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.Text): + Returns a text response. + payload (google.protobuf.struct_pb2.Struct): + Returns a response containing a custom, + platform-specific payload. + conversation_success (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.ConversationSuccess): + Indicates that the conversation succeeded. + output_audio_text (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.OutputAudioText): + A text or ssml response that is + preferentially used for TTS output audio + synthesis, as described in the comment on the + ResponseMessage message. + live_agent_handoff (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.LiveAgentHandoff): + Hands off conversation to a human agent. + end_interaction (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.EndInteraction): + Output only. A signal that indicates the interaction with + the Dialogflow agent has ended. This message is generated by + Dialogflow only when the conversation reaches + ``END_SESSION`` page. It is not supposed to be defined by + the user. + + It's guaranteed that there is at most one such message in + each response. + play_audio (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.PlayAudio): + Signal that the client should play an audio clip hosted at a + client-specific URI. Dialogflow uses this to construct + [mixed_audio][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.mixed_audio]. + However, Dialogflow itself does not try to read or process + the URI in any way. + mixed_audio (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.MixedAudio): + Output only. An audio response message composed of both the + synthesized Dialogflow agent responses and responses defined + via + [play_audio][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.play_audio]. + This message is generated by Dialogflow only and not + supposed to be defined by the user. + """ + + class Text(proto.Message): + r"""The text response message. + Attributes: + text (Sequence[str]): + Required. A collection of text responses. + allow_playback_interruption (bool): + Output only. Whether the playback of this + message can be interrupted by the end user's + speech and the client can then starts the next + Dialogflow request. + """ + + text = proto.RepeatedField( + proto.STRING, + number=1, + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=2, + ) + + class LiveAgentHandoff(proto.Message): + r"""Indicates that the conversation should be handed off to a live + 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][google.cloud.dialogflow.cx.v3beta1.Page.entry_fulfillment] + of a [Page][google.cloud.dialogflow.cx.v3beta1.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 ConversationSuccess(proto.Message): + r"""Indicates that the conversation succeeded, i.e., the bot handled the + issue that the customer talked to it about. + + Dialogflow only uses this to determine which conversations should be + counted as successful and doesn't process the metadata in this + message in any way. Note that Dialogflow also considers + conversations that get to the conversation end page as successful + even if they don't return + [ConversationSuccess][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.ConversationSuccess]. + + You may set this, for example: + + - In the + [entry_fulfillment][google.cloud.dialogflow.cx.v3beta1.Page.entry_fulfillment] + of a [Page][google.cloud.dialogflow.cx.v3beta1.Page] if entering + the page indicates that the conversation succeeded. + - In a webhook response when you determine that you handled the + customer issue. + + Attributes: + metadata (google.protobuf.struct_pb2.Struct): + Custom metadata. Dialogflow doesn't impose + any structure on this. + """ + + metadata = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + class OutputAudioText(proto.Message): + r"""A text or ssml response that is preferentially used for TTS + output audio synthesis, as described in the comment on the + ResponseMessage message. + + Attributes: + text (str): + The raw text to be synthesized. + ssml (str): + The SSML text to be synthesized. For more information, see + `SSML `__. + allow_playback_interruption (bool): + Output only. Whether the playback of this + message can be interrupted by the end user's + speech and the client can then starts the next + Dialogflow request. + """ + + text = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + ssml = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=3, + ) + + class EndInteraction(proto.Message): + r"""Indicates that interaction with the Dialogflow agent has + ended. This message is generated by Dialogflow only and not + supposed to be defined by the user. + """ + + class PlayAudio(proto.Message): + r"""Specifies an audio clip to be played by the client as part of + the response. + + Attributes: + audio_uri (str): + Required. URI of the audio clip. Dialogflow + does not impose any validation on this value. It + is specific to the client that reads it. + allow_playback_interruption (bool): + Output only. Whether the playback of this + message can be interrupted by the end user's + speech and the client can then starts the next + Dialogflow request. + """ + + audio_uri = proto.Field( + proto.STRING, + number=1, + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=2, + ) + + class MixedAudio(proto.Message): + r"""Represents an audio message that is composed of both segments + synthesized from the Dialogflow agent prompts and ones hosted + externally at the specified URIs. The external URIs are specified + via + [play_audio][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.play_audio]. + This message is generated by Dialogflow only and not supposed to be + defined by the user. + + Attributes: + segments (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.MixedAudio.Segment]): + Segments this audio response is composed of. + """ + + class Segment(proto.Message): + r"""Represents one segment of audio. + Attributes: + audio (bytes): + Raw audio synthesized from the Dialogflow + agent's response using the output config + specified in the request. + uri (str): + Client-specific URI that points to an audio + clip accessible to the client. Dialogflow does + not impose any validation on it. + allow_playback_interruption (bool): + Output only. Whether the playback of this + segment can be interrupted by the end user's + speech and the client should then start the next + Dialogflow request. + """ + + audio = proto.Field( + proto.BYTES, + number=1, + oneof='content', + ) + uri = proto.Field( + proto.STRING, + number=2, + oneof='content', + ) + allow_playback_interruption = proto.Field( + proto.BOOL, + number=3, + ) + + segments = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ResponseMessage.MixedAudio.Segment', + ) + + text = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message=Text, + ) + payload = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message=struct_pb2.Struct, + ) + conversation_success = proto.Field( + proto.MESSAGE, + number=9, + oneof='message', + message=ConversationSuccess, + ) + output_audio_text = proto.Field( + proto.MESSAGE, + number=8, + oneof='message', + message=OutputAudioText, + ) + live_agent_handoff = proto.Field( + proto.MESSAGE, + number=10, + oneof='message', + message=LiveAgentHandoff, + ) + end_interaction = proto.Field( + proto.MESSAGE, + number=11, + oneof='message', + message=EndInteraction, + ) + play_audio = proto.Field( + proto.MESSAGE, + number=12, + oneof='message', + message=PlayAudio, + ) + mixed_audio = proto.Field( + proto.MESSAGE, + number=13, + oneof='message', + message=MixedAudio, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/security_settings.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/security_settings.py new file mode 100644 index 00000000..20604349 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/security_settings.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cx.v3beta1', + manifest={ + 'GetSecuritySettingsRequest', + 'UpdateSecuritySettingsRequest', + 'ListSecuritySettingsRequest', + 'ListSecuritySettingsResponse', + 'CreateSecuritySettingsRequest', + 'DeleteSecuritySettingsRequest', + 'SecuritySettings', + }, +) + + +class GetSecuritySettingsRequest(proto.Message): + r"""The request message for + [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.GetSecuritySettings]. + + Attributes: + name (str): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSecuritySettingsRequest(proto.Message): + r"""The request message for + [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings]. + + Attributes: + security_settings (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings): + Required. [SecuritySettings] object that contains values for + each of the fields 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. + """ + + security_settings = proto.Field( + proto.MESSAGE, + number=1, + message='SecuritySettings', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.ListSecuritySettings][]. + Attributes: + parent (str): + Required. The location to list all security settings for. + Format: ``projects//locations/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 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 ListSecuritySettingsResponse(proto.Message): + r"""The response message for [SecuritySettings.ListSecuritySettings][]. + Attributes: + security_settings (Sequence[google.cloud.dialogflowcx_v3beta1.types.SecuritySettings]): + The list of security settings. + 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 + + security_settings = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SecuritySettings', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.CreateSecuritySettings][]. + Attributes: + parent (str): + Required. The location to create an + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + for. Format: + ``projects//locations/``. + security_settings (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings): + Required. The security settings to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + security_settings = proto.Field( + proto.MESSAGE, + number=2, + message='SecuritySettings', + ) + + +class DeleteSecuritySettingsRequest(proto.Message): + r"""The request message for [SecuritySettings.DeleteSecuritySettings][]. + Attributes: + name (str): + Required. The name of the + [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] + to delete. Format: + ``projects//locations//securitySettings/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class SecuritySettings(proto.Message): + r"""Represents the settings related to security issues, such as + data redaction and data retention. It may take hours for updates + on the settings to propagate to all the related components and + take effect. + + Attributes: + name (str): + Required. Resource name of the settings. Format: + ``projects//locations//securitySettings/``. + display_name (str): + Required. The human-readable name of the + security settings, unique within the location. + redaction_strategy (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings.RedactionStrategy): + Strategy that defines how we do redaction. + redaction_scope (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings.RedactionScope): + Defines the data for which Dialogflow applies + redaction. Dialogflow does not redact data that + it does not have access to – for example, Cloud + logging. + inspect_template (str): + DLP inspect template name. Use this template to define + inspect base settings. + + If empty, we use the default DLP inspect config. + + The template name will have one of the following formats: + ``projects/PROJECT_ID/inspectTemplates/TEMPLATE_ID`` OR + ``organizations/ORGANIZATION_ID/inspectTemplates/TEMPLATE_ID`` + retention_window_days (int): + Retains data in interaction logging for the + specified number of days. This does not apply to + Cloud logging, which is owned by the user - not + Dialogflow. + User must Set a value lower than Dialogflow's + default 30d TTL. Setting a value higher than + that has no effect. + A missing value or setting to 0 also means we + use Dialogflow's default TTL. + Note: Interaction logging is a limited access + feature. Talk to your Google representative to + check availability for you. + purge_data_types (Sequence[google.cloud.dialogflowcx_v3beta1.types.SecuritySettings.PurgeDataType]): + List of types of data to remove when + retention settings triggers purge. + """ + class RedactionStrategy(proto.Enum): + r"""Defines how we redact data.""" + REDACTION_STRATEGY_UNSPECIFIED = 0 + REDACT_WITH_SERVICE = 1 + + class RedactionScope(proto.Enum): + r"""Defines what types of data to redact.""" + REDACTION_SCOPE_UNSPECIFIED = 0 + REDACT_DISK_STORAGE = 2 + + class PurgeDataType(proto.Enum): + r"""Type of data we purge after retention settings triggers + purge. + """ + PURGE_DATA_TYPE_UNSPECIFIED = 0 + DIALOGFLOW_HISTORY = 1 + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + redaction_strategy = proto.Field( + proto.ENUM, + number=3, + enum=RedactionStrategy, + ) + redaction_scope = proto.Field( + proto.ENUM, + number=4, + enum=RedactionScope, + ) + inspect_template = proto.Field( + proto.STRING, + number=9, + ) + retention_window_days = proto.Field( + proto.INT32, + number=6, + oneof='data_retention', + ) + purge_data_types = proto.RepeatedField( + proto.ENUM, + number=8, + enum=PurgeDataType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session.py new file mode 100644 index 00000000..beba7b99 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session.py @@ -0,0 +1,1172 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import audio_config +from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import response_message +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type +from google.protobuf import duration_pb2 # 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.cx.v3beta1', + manifest={ + 'DetectIntentRequest', + 'DetectIntentResponse', + 'StreamingDetectIntentRequest', + 'StreamingDetectIntentResponse', + 'StreamingRecognitionResult', + 'QueryParameters', + 'QueryInput', + 'QueryResult', + 'TextInput', + 'IntentInput', + 'AudioInput', + 'EventInput', + 'DtmfInput', + 'Match', + 'MatchIntentRequest', + 'MatchIntentResponse', + 'FulfillIntentRequest', + 'FulfillIntentResponse', + 'SentimentAnalysisResult', + }, +) + + +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//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. It's up to the API caller to choose an + appropriate ``Session ID``. It can be a random number or + some type of session identifiers (preferably hashed). The + length of the ``Session ID`` must not exceed 36 characters. + + For more information, see the `sessions + guide `__. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + query_params (google.cloud.dialogflowcx_v3beta1.types.QueryParameters): + The parameters of this query. + query_input (google.cloud.dialogflowcx_v3beta1.types.QueryInput): + Required. The input specification. + output_audio_config (google.cloud.dialogflowcx_v3beta1.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate the output audio. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=4, + message=audio_config.OutputAudioConfig, + ) + + +class DetectIntentResponse(proto.Message): + r"""The message returned from the DetectIntent method. + Attributes: + response_id (str): + Output only. 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.dialogflowcx_v3beta1.types.QueryResult): + The result of the conversational query. + 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.response_messages``][google.cloud.dialogflow.cx.v3beta1.QueryResult.response_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.dialogflowcx_v3beta1.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', + ) + output_audio = proto.Field( + proto.BYTES, + number=4, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=5, + message=audio_config.OutputAudioConfig, + ) + + +class StreamingDetectIntentRequest(proto.Message): + r"""The top-level message sent by the client to the + [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.StreamingDetectIntent] + method. + + Multiple request messages should be sent in order: + + 1. The first message must contain + [session][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.session], + [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] + plus optionally + [query_params][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_params]. + If the client wants to receive an audio response, it should also + contain + [output_audio_config][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.output_audio_config]. + + 2. If + [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] + was set to + [query_input.audio.config][google.cloud.dialogflow.cx.v3beta1.AudioInput.config], + all subsequent messages must contain + [query_input.audio.audio][google.cloud.dialogflow.cx.v3beta1.AudioInput.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.cx.v3beta1.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): + The name of the session this query is sent to. Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. It's up to the API caller to choose an + appropriate ``Session ID``. It can be a random number or + some type of session identifiers (preferably hashed). The + length of the ``Session ID`` must not exceed 36 characters. + Note: session must be set in the first request. + + For more information, see the `sessions + guide `__. + + Note: Always use agent versions for production traffic. See + `Versions and + environments `__. + query_params (google.cloud.dialogflowcx_v3beta1.types.QueryParameters): + The parameters of this query. + query_input (google.cloud.dialogflowcx_v3beta1.types.QueryInput): + Required. The input specification. + output_audio_config (google.cloud.dialogflowcx_v3beta1.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate the output audio. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=4, + message=audio_config.OutputAudioConfig, + ) + + +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. If ``enable_partial_response`` is true, the following N messages + (currently 1 <= N <= 4) contain ``detect_intent_response``. The + first (N-1) ``detect_intent_response``\ s will have + ``response_type`` set to ``PARTIAL``. The last + ``detect_intent_response`` has ``response_type`` set to + ``FINAL``. If ``response_type`` is false, response stream only + contains the final ``detect_intent_response``. + + Attributes: + recognition_result (google.cloud.dialogflowcx_v3beta1.types.StreamingRecognitionResult): + The result of speech recognition. + detect_intent_response (google.cloud.dialogflowcx_v3beta1.types.DetectIntentResponse): + The response from detect intent. + """ + + recognition_result = proto.Field( + proto.MESSAGE, + number=1, + oneof='response', + message='StreamingRecognitionResult', + ) + detect_intent_response = proto.Field( + proto.MESSAGE, + number=2, + oneof='response', + message='DetectIntentResponse', + ) + + +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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.SpeechWordInfo]): + Word-specific information for the words recognized by Speech + in + [transcript][google.cloud.dialogflow.cx.v3beta1.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, + ) + stability = proto.Field( + proto.FLOAT, + number=6, + ) + speech_word_info = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=audio_config.SpeechWordInfo, + ) + speech_end_offset = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class QueryParameters(proto.Message): + r"""Represents the parameters of a conversational query. + Attributes: + time_zone (str): + The time zone of this conversational query from the `time + zone database `__, e.g., + America/New_York, Europe/Paris. If not provided, the time + zone specified in the agent is used. + geo_location (google.type.latlng_pb2.LatLng): + The geo location of this conversational + query. + session_entity_types (Sequence[google.cloud.dialogflowcx_v3beta1.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 into the webhook + associated with the agent. Arbitrary JSON objects are + supported. Some integrations that query a Dialogflow agent + may provide additional information in the payload. In + particular, for the Dialogflow Phone Gateway integration, + this field has the form: + + :: + + { + "telephony": { + "caller_id": "+18558363987" + } + } + parameters (google.protobuf.struct_pb2.Struct): + Additional parameters to be put into [session + parameters][SessionInfo.parameters]. To remove a parameter + from the session, clients should explicitly set the + parameter value to null. + + You can reference the session parameters in the agent with + the following format: $session.params.parameter-id. + + 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 + current_page (str): + The unique identifier of the + [page][google.cloud.dialogflow.cx.v3beta1.Page] to override + the [current page][QueryResult.current_page] in the session. + Format: + ``projects//locations//agents//pages/``. + + If ``current_page`` is specified, the previous state of the + session will be ignored by Dialogflow, including the + [previous page][QueryResult.current_page] and the [previous + session parameters][QueryResult.parameters]. In most cases, + [current_page][google.cloud.dialogflow.cx.v3beta1.QueryParameters.current_page] + and + [parameters][google.cloud.dialogflow.cx.v3beta1.QueryParameters.parameters] + should be configured together to direct a session to a + specific state. + disable_webhook (bool): + Whether to disable webhook calls for this + request. + analyze_query_text_sentiment (bool): + Configures whether sentiment analysis should + be performed. If not provided, sentiment + analysis is not performed. + webhook_headers (Sequence[google.cloud.dialogflowcx_v3beta1.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, + ) + session_entity_types = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=session_entity_type.SessionEntityType, + ) + payload = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + parameters = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) + current_page = proto.Field( + proto.STRING, + number=6, + ) + disable_webhook = proto.Field( + proto.BOOL, + number=7, + ) + analyze_query_text_sentiment = proto.Field( + proto.BOOL, + number=8, + ) + webhook_headers = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + + +class QueryInput(proto.Message): + r"""Represents the query input. It can contain one of: + 1. A conversational query in the form of text. + + 2. An intent query that specifies which intent to trigger. + 3. Natural language speech audio to be processed. + + 4. An event to be triggered. + + Attributes: + text (google.cloud.dialogflowcx_v3beta1.types.TextInput): + The natural language text to be processed. + intent (google.cloud.dialogflowcx_v3beta1.types.IntentInput): + The intent to be triggered. + audio (google.cloud.dialogflowcx_v3beta1.types.AudioInput): + The natural language speech audio to be + processed. + event (google.cloud.dialogflowcx_v3beta1.types.EventInput): + The event to be triggered. + dtmf (google.cloud.dialogflowcx_v3beta1.types.DtmfInput): + The DTMF event to be handled. + language_code (str): + Required. The language of the input. 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.MESSAGE, + number=2, + oneof='input', + message='TextInput', + ) + intent = proto.Field( + proto.MESSAGE, + number=3, + oneof='input', + message='IntentInput', + ) + audio = proto.Field( + proto.MESSAGE, + number=5, + oneof='input', + message='AudioInput', + ) + event = proto.Field( + proto.MESSAGE, + number=6, + oneof='input', + message='EventInput', + ) + dtmf = proto.Field( + proto.MESSAGE, + number=7, + oneof='input', + message='DtmfInput', + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class QueryResult(proto.Message): + r"""Represents the result of a conversational query. + Attributes: + text (str): + If [natural language + text][google.cloud.dialogflow.cx.v3beta1.TextInput] was + provided as input, this field will contain a copy of the + text. + trigger_intent (str): + If an + [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was + provided as input, this field will contain a copy of the + intent identifier. Format: + ``projects//locations//agents//intents/``. + transcript (str): + If [natural language speech + audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was + provided as input, this field will contain the transcript + for the audio. + trigger_event (str): + If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] + was provided as input, this field will contain the name of + the event. + language_code (str): + The language that was triggered during intent detection. See + `Language + Support `__ + for a list of the currently supported language codes. + parameters (google.protobuf.struct_pb2.Struct): + The collected [session + parameters][google.cloud.dialogflow.cx.v3beta1.SessionInfo.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 + response_messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage]): + The list of rich messages returned to the + client. Responses vary from simple text messages + to more sophisticated, structured payloads used + to drive complex logic. + webhook_statuses (Sequence[google.rpc.status_pb2.Status]): + The list of webhook call status in the order + of call sequence. + webhook_payloads (Sequence[google.protobuf.struct_pb2.Struct]): + The list of webhook payload in + [WebhookResponse.payload][google.cloud.dialogflow.cx.v3beta1.WebhookResponse.payload], + in the order of call sequence. If some webhook call fails or + doesn't return any payload, an empty ``Struct`` would be + used instead. + current_page (google.cloud.dialogflowcx_v3beta1.types.Page): + The current [Page][google.cloud.dialogflow.cx.v3beta1.Page]. + Some, not all fields are filled in this message, including + but not limited to ``name`` and ``display_name``. + intent (google.cloud.dialogflowcx_v3beta1.types.Intent): + The [Intent][google.cloud.dialogflow.cx.v3beta1.Intent] that + matched the conversational query. Some, not all fields are + filled in this message, including but not limited to: + ``name`` and ``display_name``. This field is deprecated, + please use + [QueryResult.match][google.cloud.dialogflow.cx.v3beta1.QueryResult.match] + instead. + 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. This field is deprecated, please use + [QueryResult.match][google.cloud.dialogflow.cx.v3beta1.QueryResult.match] + instead. + match (google.cloud.dialogflowcx_v3beta1.types.Match): + Intent match result, could be an intent or an + event. + diagnostic_info (google.protobuf.struct_pb2.Struct): + The free-form diagnostic info. For example, + this field could contain webhook call latency. + The string keys of the Struct's fields map can + change without notice. + sentiment_analysis_result (google.cloud.dialogflowcx_v3beta1.types.SentimentAnalysisResult): + The sentiment analyss result, which depends on + [``analyze_query_text_sentiment``] + [google.cloud.dialogflow.cx.v3beta1.QueryParameters.analyze_query_text_sentiment], + specified in the request. + """ + + text = proto.Field( + proto.STRING, + number=1, + oneof='query', + ) + trigger_intent = proto.Field( + proto.STRING, + number=11, + oneof='query', + ) + transcript = proto.Field( + proto.STRING, + number=12, + oneof='query', + ) + trigger_event = proto.Field( + proto.STRING, + number=14, + oneof='query', + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + parameters = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + response_messages = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=response_message.ResponseMessage, + ) + webhook_statuses = proto.RepeatedField( + proto.MESSAGE, + number=13, + message=status_pb2.Status, + ) + webhook_payloads = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + current_page = proto.Field( + proto.MESSAGE, + number=7, + message=page.Page, + ) + intent = proto.Field( + proto.MESSAGE, + number=8, + message=gcdc_intent.Intent, + ) + intent_detection_confidence = proto.Field( + proto.FLOAT, + number=9, + ) + match = proto.Field( + proto.MESSAGE, + number=15, + message='Match', + ) + diagnostic_info = proto.Field( + proto.MESSAGE, + number=10, + message=struct_pb2.Struct, + ) + sentiment_analysis_result = proto.Field( + proto.MESSAGE, + number=17, + message='SentimentAnalysisResult', + ) + + +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. + """ + + text = proto.Field( + proto.STRING, + number=1, + ) + + +class IntentInput(proto.Message): + r"""Represents the intent to trigger programmatically rather than + as a result of natural language processing. + + Attributes: + intent (str): + Required. The unique identifier of the intent. Format: + ``projects//locations//agents//intents/``. + """ + + intent = proto.Field( + proto.STRING, + number=1, + ) + + +class AudioInput(proto.Message): + r"""Represents the natural speech audio to be processed. + Attributes: + config (google.cloud.dialogflowcx_v3beta1.types.InputAudioConfig): + Required. Instructs the speech recognizer how + to process the speech audio. + audio (bytes): + The natural language speech audio to be processed. A single + request can contain up to 1 minute of speech audio data. The + [transcribed + text][google.cloud.dialogflow.cx.v3beta1.QueryResult.transcript] + cannot contain more than 256 bytes. + + For non-streaming audio detect intent, both ``config`` and + ``audio`` must be provided. For streaming audio detect + intent, ``config`` must be provided in the first request and + ``audio`` must be provided in all following requests. + """ + + config = proto.Field( + proto.MESSAGE, + number=1, + message=audio_config.InputAudioConfig, + ) + audio = proto.Field( + proto.BYTES, + number=2, + ) + + +class EventInput(proto.Message): + r"""Represents the event to trigger. + Attributes: + event (str): + Name of the event. + """ + + event = proto.Field( + proto.STRING, + number=1, + ) + + +class DtmfInput(proto.Message): + r"""Represents the input for dtmf event. + Attributes: + digits (str): + The dtmf digits. + finish_digit (str): + The finish digit (if any). + """ + + digits = proto.Field( + proto.STRING, + number=1, + ) + finish_digit = proto.Field( + proto.STRING, + number=2, + ) + + +class Match(proto.Message): + r"""Represents one match result of [MatchIntent][]. + Attributes: + intent (google.cloud.dialogflowcx_v3beta1.types.Intent): + The [Intent][google.cloud.dialogflow.cx.v3beta1.Intent] that + matched the query. Some, not all fields are filled in this + message, including but not limited to: ``name`` and + ``display_name``. Only filled for + [``INTENT``][google.cloud.dialogflow.cx.v3beta1.Match.MatchType] + match type. + event (str): + The event that matched the query. Only filled for + [``EVENT``][google.cloud.dialogflow.cx.v3beta1.Match.MatchType] + match type. + parameters (google.protobuf.struct_pb2.Struct): + The collection of parameters extracted from + the query. + 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 + resolved_input (str): + Final text input which was matched during + MatchIntent. This value can be different from + original input sent in request because of + spelling correction or other processing. + match_type (google.cloud.dialogflowcx_v3beta1.types.Match.MatchType): + Type of this + [Match][google.cloud.dialogflow.cx.v3beta1.Match]. + confidence (float): + The confidence of this match. Values range + from 0.0 (completely uncertain) to 1.0 + (completely certain). This value is for + informational purpose only and is only used to + help match the best intent within the + classification threshold. This value may change + for the same end-user expression at any time due + to a model retraining or change in + implementation. + """ + class MatchType(proto.Enum): + r"""Type of a Match.""" + MATCH_TYPE_UNSPECIFIED = 0 + INTENT = 1 + DIRECT_INTENT = 2 + PARAMETER_FILLING = 3 + NO_MATCH = 4 + NO_INPUT = 5 + EVENT = 6 + + intent = proto.Field( + proto.MESSAGE, + number=1, + message=gcdc_intent.Intent, + ) + event = proto.Field( + proto.STRING, + number=6, + ) + parameters = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + resolved_input = proto.Field( + proto.STRING, + number=3, + ) + match_type = proto.Field( + proto.ENUM, + number=4, + enum=MatchType, + ) + confidence = proto.Field( + proto.FLOAT, + number=5, + ) + + +class MatchIntentRequest(proto.Message): + r"""Request of [MatchIntent][]. + Attributes: + session (str): + Required. The name of the session this query is sent to. + Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. It's up to the API caller to choose an + appropriate ``Session ID``. It can be a random number or + some type of session identifiers (preferably hashed). The + length of the ``Session ID`` must not exceed 36 characters. + + For more information, see the `sessions + guide `__. + query_params (google.cloud.dialogflowcx_v3beta1.types.QueryParameters): + The parameters of this query. + query_input (google.cloud.dialogflowcx_v3beta1.types.QueryInput): + Required. The input specification. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + query_params = proto.Field( + proto.MESSAGE, + number=2, + message='QueryParameters', + ) + query_input = proto.Field( + proto.MESSAGE, + number=3, + message='QueryInput', + ) + + +class MatchIntentResponse(proto.Message): + r"""Response of [MatchIntent][]. + Attributes: + text (str): + If [natural language + text][google.cloud.dialogflow.cx.v3beta1.TextInput] was + provided as input, this field will contain a copy of the + text. + trigger_intent (str): + If an + [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was + provided as input, this field will contain a copy of the + intent identifier. Format: + ``projects//locations//agents//intents/``. + transcript (str): + If [natural language speech + audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was + provided as input, this field will contain the transcript + for the audio. + trigger_event (str): + If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] + was provided as input, this field will contain a copy of the + event name. + matches (Sequence[google.cloud.dialogflowcx_v3beta1.types.Match]): + Match results, if more than one, ordered + descendingly by the confidence we have that the + particular intent matches the query. + current_page (google.cloud.dialogflowcx_v3beta1.types.Page): + The current [Page][google.cloud.dialogflow.cx.v3beta1.Page]. + Some, not all fields are filled in this message, including + but not limited to ``name`` and ``display_name``. + """ + + text = proto.Field( + proto.STRING, + number=1, + oneof='query', + ) + trigger_intent = proto.Field( + proto.STRING, + number=2, + oneof='query', + ) + transcript = proto.Field( + proto.STRING, + number=3, + oneof='query', + ) + trigger_event = proto.Field( + proto.STRING, + number=6, + oneof='query', + ) + matches = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Match', + ) + current_page = proto.Field( + proto.MESSAGE, + number=5, + message=page.Page, + ) + + +class FulfillIntentRequest(proto.Message): + r"""Request of [FulfillIntent][] + Attributes: + match_intent_request (google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest): + Must be same as the corresponding MatchIntent + request, otherwise the behavior is undefined. + match (google.cloud.dialogflowcx_v3beta1.types.Match): + The matched intent/event to fulfill. + output_audio_config (google.cloud.dialogflowcx_v3beta1.types.OutputAudioConfig): + Instructs the speech synthesizer how to + generate output audio. + """ + + match_intent_request = proto.Field( + proto.MESSAGE, + number=1, + message='MatchIntentRequest', + ) + match = proto.Field( + proto.MESSAGE, + number=2, + message='Match', + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=3, + message=audio_config.OutputAudioConfig, + ) + + +class FulfillIntentResponse(proto.Message): + r"""Response of [FulfillIntent][] + Attributes: + response_id (str): + Output only. 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.dialogflowcx_v3beta1.types.QueryResult): + The result of the conversational query. + 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.response_messages``][google.cloud.dialogflow.cx.v3beta1.QueryResult.response_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.dialogflowcx_v3beta1.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', + ) + output_audio = proto.Field( + proto.BYTES, + number=3, + ) + output_audio_config = proto.Field( + proto.MESSAGE, + number=4, + message=audio_config.OutputAudioConfig, + ) + + +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. + + 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/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py new file mode 100644 index 00000000..df46a297 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.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 proto # type: ignore + +from google.cloud.dialogflowcx_v3beta1.types import entity_type +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'SessionEntityType', + 'ListSessionEntityTypesRequest', + 'ListSessionEntityTypesResponse', + 'GetSessionEntityTypeRequest', + 'CreateSessionEntityTypeRequest', + 'UpdateSessionEntityTypeRequest', + 'DeleteSessionEntityTypeRequest', + }, +) + + +class SessionEntityType(proto.Message): + r"""Session entity types are referred to as **User** entity types and + are entities that are built for an individual user such as + favorites, preferences, playlists, and so on. + + You can redefine a session entity type at the session level to + extend or replace a [custom entity + type][google.cloud.dialogflow.cx.v3beta1.EntityType] at the user + session level (we refer to the entity types defined at the agent + level as "custom entity types"). + + Note: session entity types apply to all queries, regardless of the + language. + + For more information about entity types, see the `Dialogflow + documentation `__. + + Attributes: + name (str): + Required. The unique identifier of the session entity type. + Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + entity_override_mode (google.cloud.dialogflowcx_v3beta1.types.SessionEntityType.EntityOverrideMode): + Required. Indicates whether the additional + data should override or supplement the custom + entity type definition. + entities (Sequence[google.cloud.dialogflowcx_v3beta1.types.EntityType.Entity]): + Required. The collection of entities to + override or supplement the custom entity type. + """ + class EntityOverrideMode(proto.Enum): + r"""The types of modifications for the 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=3, + enum=EntityOverrideMode, + ) + entities = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=entity_type.EntityType.Entity, + ) + + +class ListSessionEntityTypesRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.ListSessionEntityTypes]. + + Attributes: + parent (str): + Required. The session to list all session entity types from. + Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + 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 ListSessionEntityTypesResponse(proto.Message): + r"""The response message for + [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.ListSessionEntityTypes]. + + Attributes: + session_entity_types (Sequence[google.cloud.dialogflowcx_v3beta1.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.cx.v3beta1.SessionEntityTypes.GetSessionEntityType]. + + Attributes: + name (str): + Required. The name of the session entity type. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSessionEntityTypeRequest(proto.Message): + r"""The request message for + [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.CreateSessionEntityType]. + + Attributes: + parent (str): + Required. The session to create a session entity type for. + Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + session_entity_type (google.cloud.dialogflowcx_v3beta1.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.cx.v3beta1.SessionEntityTypes.UpdateSessionEntityType]. + + Attributes: + session_entity_type (google.cloud.dialogflowcx_v3beta1.types.SessionEntityType): + Required. The session entity type to update. Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + 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.cx.v3beta1.SessionEntityTypes.DeleteSessionEntityType]. + + Attributes: + name (str): + Required. The name of the session entity type to delete. + Format: + ``projects//locations//agents//sessions//entityTypes/`` + or + ``projects//locations//agents//environments//sessions//entityTypes/``. + If ``Environment ID`` is not specified, we assume default + 'draft' environment. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/test_case.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/test_case.py new file mode 100644 index 00000000..210f2127 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/test_case.py @@ -0,0 +1,1250 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import flow as gcdc_flow +from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent +from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page +from google.cloud.dialogflowcx_v3beta1.types import response_message +from google.cloud.dialogflowcx_v3beta1.types import session +from google.cloud.dialogflowcx_v3beta1.types import transition_route_group +from google.protobuf import field_mask_pb2 # 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.cx.v3beta1', + manifest={ + 'TestResult', + 'TestCase', + 'TestCaseResult', + 'TestConfig', + 'ConversationTurn', + 'TestRunDifference', + 'TransitionCoverage', + 'TransitionRouteGroupCoverage', + 'IntentCoverage', + 'CalculateCoverageRequest', + 'CalculateCoverageResponse', + 'ListTestCasesRequest', + 'ListTestCasesResponse', + 'BatchDeleteTestCasesRequest', + 'CreateTestCaseRequest', + 'UpdateTestCaseRequest', + 'GetTestCaseRequest', + 'RunTestCaseRequest', + 'RunTestCaseResponse', + 'RunTestCaseMetadata', + 'BatchRunTestCasesRequest', + 'BatchRunTestCasesResponse', + 'BatchRunTestCasesMetadata', + 'TestError', + 'ImportTestCasesRequest', + 'ImportTestCasesResponse', + 'ImportTestCasesMetadata', + 'TestCaseError', + 'ExportTestCasesRequest', + 'ExportTestCasesResponse', + 'ExportTestCasesMetadata', + 'ListTestCaseResultsRequest', + 'ListTestCaseResultsResponse', + 'GetTestCaseResultRequest', + }, +) + + +class TestResult(proto.Enum): + r"""The test result for a test case and an agent environment.""" + TEST_RESULT_UNSPECIFIED = 0 + PASSED = 1 + FAILED = 2 + + +class TestCase(proto.Message): + r"""Represents a test case. + Attributes: + name (str): + The unique identifier of the test case. + [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.CreateTestCase] + will populate the name automatically. Otherwise use format: + ``projects//locations//agents/ /testCases/``. + tags (Sequence[str]): + Tags are short descriptions that users may + apply to test cases for organizational and + filtering purposes. Each tag should start with + "#" and has a limit of 30 characters. + display_name (str): + Required. The human-readable name of the test + case, unique within the agent. Limit of 200 + characters. + notes (str): + Additional freeform notes about the test + case. Limit of 400 characters. + test_config (google.cloud.dialogflowcx_v3beta1.types.TestConfig): + Config for the test case. + test_case_conversation_turns (Sequence[google.cloud.dialogflowcx_v3beta1.types.ConversationTurn]): + The conversation turns uttered when the test + case was created, in chronological order. These + include the canonical set of agent utterances + that should occur when the agent is working + properly. + creation_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the test was created. + last_test_result (google.cloud.dialogflowcx_v3beta1.types.TestCaseResult): + The latest test result. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + tags = proto.RepeatedField( + proto.STRING, + number=2, + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + notes = proto.Field( + proto.STRING, + number=4, + ) + test_config = proto.Field( + proto.MESSAGE, + number=13, + message='TestConfig', + ) + test_case_conversation_turns = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='ConversationTurn', + ) + creation_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + last_test_result = proto.Field( + proto.MESSAGE, + number=12, + message='TestCaseResult', + ) + + +class TestCaseResult(proto.Message): + r"""Represents a result from running a test case in an agent + environment. + + Attributes: + name (str): + The resource name for the test case result. Format: + ``projects//locations//agents//testCases/ /results/``. + environment (str): + Environment where the test was run. If not + set, it indicates the draft environment. + conversation_turns (Sequence[google.cloud.dialogflowcx_v3beta1.types.ConversationTurn]): + The conversation turns uttered during the + test case replay in chronological order. + test_result (google.cloud.dialogflowcx_v3beta1.types.TestResult): + Whether the test case passed in the agent + environment. + test_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the test was run. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.STRING, + number=2, + ) + conversation_turns = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ConversationTurn', + ) + test_result = proto.Field( + proto.ENUM, + number=4, + enum='TestResult', + ) + test_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class TestConfig(proto.Message): + r"""Represents configurations for a test case. + Attributes: + tracking_parameters (Sequence[str]): + Session parameters to be compared when + calculating differences. + flow (str): + Flow name. If not set, default start flow is assumed. + Format: + ``projects//locations//agents//flows/``. + """ + + tracking_parameters = proto.RepeatedField( + proto.STRING, + number=1, + ) + flow = proto.Field( + proto.STRING, + number=2, + ) + + +class ConversationTurn(proto.Message): + r"""One interaction between a human and virtual agent. The human + provides some input and the virtual agent provides a response. + + Attributes: + user_input (google.cloud.dialogflowcx_v3beta1.types.ConversationTurn.UserInput): + The user input. + virtual_agent_output (google.cloud.dialogflowcx_v3beta1.types.ConversationTurn.VirtualAgentOutput): + The virtual agent output. + """ + + class UserInput(proto.Message): + r"""The input from the human user. + Attributes: + input (google.cloud.dialogflowcx_v3beta1.types.QueryInput): + Supports [text + input][google.cloud.dialogflow.cx.v3beta1.QueryInput.text], + [event + input][google.cloud.dialogflow.cx.v3beta1.QueryInput.event], + [dtmf + input][google.cloud.dialogflow.cx.v3beta1.QueryInput.dtmf] + in the test case. + injected_parameters (google.protobuf.struct_pb2.Struct): + Parameters that need to be injected into the + conversation during intent detection. + is_webhook_enabled (bool): + If webhooks should be allowed to trigger in + response to the user utterance. Often if + parameters are injected, webhooks should not be + enabled. + """ + + input = proto.Field( + proto.MESSAGE, + number=5, + message=session.QueryInput, + ) + injected_parameters = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + is_webhook_enabled = proto.Field( + proto.BOOL, + number=3, + ) + + class VirtualAgentOutput(proto.Message): + r"""The output from the virtual agent. + Attributes: + session_parameters (google.protobuf.struct_pb2.Struct): + The session parameters available to the bot + at this point. + differences (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestRunDifference]): + Output only. If this is part of a [result conversation + turn][TestCaseResult.conversation_turns], the list of + differences between the original run and the replay for this + output, if any. + diagnostic_info (google.protobuf.struct_pb2.Struct): + Required. Input only. The diagnostic + [info][Session.DetectIntentResponse.QueryResult.diagnostic_info] + output for the turn. + triggered_intent (google.cloud.dialogflowcx_v3beta1.types.Intent): + The [Intent][google.cloud.dialogflow.cx.v3beta1.Intent] that + triggered the response. Only name and displayName will be + set. + current_page (google.cloud.dialogflowcx_v3beta1.types.Page): + The [Page][google.cloud.dialogflow.cx.v3beta1.Page] on which + the utterance was spoken. Only name and displayName will be + set. + text_responses (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.Text]): + The + [text][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.Text] + responses from the agent for the turn. + status (google.rpc.status_pb2.Status): + Response error from the agent in the test + result. If set, other output is empty. + """ + + session_parameters = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + differences = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='TestRunDifference', + ) + diagnostic_info = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + triggered_intent = proto.Field( + proto.MESSAGE, + number=7, + message=gcdc_intent.Intent, + ) + current_page = proto.Field( + proto.MESSAGE, + number=8, + message=gcdc_page.Page, + ) + text_responses = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=response_message.ResponseMessage.Text, + ) + status = proto.Field( + proto.MESSAGE, + number=10, + message=status_pb2.Status, + ) + + user_input = proto.Field( + proto.MESSAGE, + number=1, + message=UserInput, + ) + virtual_agent_output = proto.Field( + proto.MESSAGE, + number=2, + message=VirtualAgentOutput, + ) + + +class TestRunDifference(proto.Message): + r"""The description of differences between original and replayed + agent output. + + Attributes: + type_ (google.cloud.dialogflowcx_v3beta1.types.TestRunDifference.DiffType): + The type of diff. + description (str): + A description of the diff, showing the actual + output vs expected output. + """ + class DiffType(proto.Enum): + r"""What part of the message replay differs from the test case.""" + DIFF_TYPE_UNSPECIFIED = 0 + INTENT = 1 + PAGE = 2 + PARAMETERS = 3 + UTTERANCE = 4 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum=DiffType, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + + +class TransitionCoverage(proto.Message): + r"""Transition coverage represents the percentage of all possible + page transitions (page-level transition routes and event + handlers, excluding transition route groups) present within any + of a parent's test cases. + + Attributes: + transitions (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage.Transition]): + The list of Transitions present in the agent. + coverage_score (float): + The percent of transitions in the agent that + are covered. + """ + + class TransitionNode(proto.Message): + r"""The source or target of a transition. + Attributes: + page (google.cloud.dialogflowcx_v3beta1.types.Page): + Indicates a transition to a + [Page][google.cloud.dialogflow.cx.v3beta1.Page]. Only some + fields such as name and displayname will be set. + flow (google.cloud.dialogflowcx_v3beta1.types.Flow): + Indicates a transition to a + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. Only some + fields such as name and displayname will be set. + """ + + page = proto.Field( + proto.MESSAGE, + number=1, + oneof='kind', + message=gcdc_page.Page, + ) + flow = proto.Field( + proto.MESSAGE, + number=2, + oneof='kind', + message=gcdc_flow.Flow, + ) + + class Transition(proto.Message): + r"""A transition in a page. + Attributes: + source (google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage.TransitionNode): + The start node of a transition. + index (int): + The index of a transition in the transition + list. Starting from 0. + target (google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage.TransitionNode): + The end node of a transition. + covered (bool): + Whether or not the transition is covered by + at least one of the agent's test cases. + transition_route (google.cloud.dialogflowcx_v3beta1.types.TransitionRoute): + Intent route or condition route. + event_handler (google.cloud.dialogflowcx_v3beta1.types.EventHandler): + Event handler. + """ + + source = proto.Field( + proto.MESSAGE, + number=1, + message='TransitionCoverage.TransitionNode', + ) + index = proto.Field( + proto.INT32, + number=4, + ) + target = proto.Field( + proto.MESSAGE, + number=2, + message='TransitionCoverage.TransitionNode', + ) + covered = proto.Field( + proto.BOOL, + number=3, + ) + transition_route = proto.Field( + proto.MESSAGE, + number=5, + oneof='detail', + message=gcdc_page.TransitionRoute, + ) + event_handler = proto.Field( + proto.MESSAGE, + number=6, + oneof='detail', + message=gcdc_page.EventHandler, + ) + + transitions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Transition, + ) + coverage_score = proto.Field( + proto.FLOAT, + number=2, + ) + + +class TransitionRouteGroupCoverage(proto.Message): + r"""Transition route group coverage represents the percentage of + all possible transition routes present within any of a parent's + test cases. The results are grouped by the transition route + group. + + Attributes: + coverages (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroupCoverage.Coverage]): + Transition route group coverages. + coverage_score (float): + The percent of transition routes in all the + transition route groups that are covered. + """ + + class Coverage(proto.Message): + r"""Coverage result message for one transition route group. + Attributes: + route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): + Transition route group metadata. Only name + and displayName will be set. + transitions (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroupCoverage.Coverage.Transition]): + The list of transition routes and coverage in + the transition route group. + coverage_score (float): + The percent of transition routes in the + transition route group that are covered. + """ + + class Transition(proto.Message): + r"""A transition coverage in a transition route group. + Attributes: + transition_route (google.cloud.dialogflowcx_v3beta1.types.TransitionRoute): + Intent route or condition route. + covered (bool): + Whether or not the transition route is + covered by at least one of the agent's test + cases. + """ + + transition_route = proto.Field( + proto.MESSAGE, + number=1, + message=gcdc_page.TransitionRoute, + ) + covered = proto.Field( + proto.BOOL, + number=2, + ) + + route_group = proto.Field( + proto.MESSAGE, + number=1, + message=transition_route_group.TransitionRouteGroup, + ) + transitions = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='TransitionRouteGroupCoverage.Coverage.Transition', + ) + coverage_score = proto.Field( + proto.FLOAT, + number=3, + ) + + coverages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Coverage, + ) + coverage_score = proto.Field( + proto.FLOAT, + number=2, + ) + + +class IntentCoverage(proto.Message): + r"""Intent coverage represents the percentage of all possible + intents in the agent that are triggered in any of a parent's + test cases. + + Attributes: + intents (Sequence[google.cloud.dialogflowcx_v3beta1.types.IntentCoverage.Intent]): + The list of Intents present in the agent + coverage_score (float): + The percent of intents in the agent that are + covered. + """ + + class Intent(proto.Message): + r"""The agent's intent. + Attributes: + intent (str): + The intent full resource name + covered (bool): + Whether or not the intent is covered by at + least one of the agent's test cases. + """ + + intent = proto.Field( + proto.STRING, + number=1, + ) + covered = proto.Field( + proto.BOOL, + number=2, + ) + + intents = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Intent, + ) + coverage_score = proto.Field( + proto.FLOAT, + number=2, + ) + + +class CalculateCoverageRequest(proto.Message): + r"""The request message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. + + Attributes: + agent (str): + Required. The agent to calculate coverage for. Format: + ``projects//locations//agents/``. + type_ (google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageRequest.CoverageType): + Required. The type of coverage requested. + """ + class CoverageType(proto.Enum): + r"""The type of coverage score requested.""" + COVERAGE_TYPE_UNSPECIFIED = 0 + INTENT = 1 + PAGE_TRANSITION = 2 + TRANSITION_ROUTE_GROUP = 3 + + agent = proto.Field( + proto.STRING, + number=3, + ) + type_ = proto.Field( + proto.ENUM, + number=2, + enum=CoverageType, + ) + + +class CalculateCoverageResponse(proto.Message): + r"""The response message for + [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. + + Attributes: + agent (str): + The agent to calculate coverage for. Format: + ``projects//locations//agents/``. + intent_coverage (google.cloud.dialogflowcx_v3beta1.types.IntentCoverage): + Intent coverage. + transition_coverage (google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage): + Transition (excluding transition route + groups) coverage. + route_group_coverage (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroupCoverage): + Transition route group coverage. + """ + + agent = proto.Field( + proto.STRING, + number=5, + ) + intent_coverage = proto.Field( + proto.MESSAGE, + number=2, + oneof='coverage_type', + message='IntentCoverage', + ) + transition_coverage = proto.Field( + proto.MESSAGE, + number=4, + oneof='coverage_type', + message='TransitionCoverage', + ) + route_group_coverage = proto.Field( + proto.MESSAGE, + number=6, + oneof='coverage_type', + message='TransitionRouteGroupCoverage', + ) + + +class ListTestCasesRequest(proto.Message): + r"""The request message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. + + Attributes: + parent (str): + Required. The agent to list all pages for. Format: + ``projects//locations//agents/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20. Note that when + TestCaseView = FULL, the maximum page size + allowed is 20. When TestCaseView = BASIC, the + maximum page size allowed is 500. + page_token (str): + The next_page_token value returned from a previous list + request. + view (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest.TestCaseView): + Specifies whether response should include all + fields or just the metadata. + """ + class TestCaseView(proto.Enum): + r"""Specifies how much test case information to include in the + response. + """ + TEST_CASE_VIEW_UNSPECIFIED = 0 + BASIC = 1 + FULL = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + view = proto.Field( + proto.ENUM, + number=4, + enum=TestCaseView, + ) + + +class ListTestCasesResponse(proto.Message): + r"""The response message for + [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. + + Attributes: + test_cases (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestCase]): + The list of test cases. 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 + + test_cases = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TestCase', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class BatchDeleteTestCasesRequest(proto.Message): + r"""The request message for + [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchDeleteTestCases]. + + Attributes: + parent (str): + Required. The agent to delete test cases from. Format: + ``projects//locations//agents/``. + names (Sequence[str]): + Required. Format of test case names: + ``projects//locations/ /agents//testCases/``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + names = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class CreateTestCaseRequest(proto.Message): + r"""The request message for + [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.CreateTestCase]. + + Attributes: + parent (str): + Required. The agent to create the test case for. Format: + ``projects//locations//agents/``. + test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): + Required. The test case to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + test_case = proto.Field( + proto.MESSAGE, + number=2, + message='TestCase', + ) + + +class UpdateTestCaseRequest(proto.Message): + r"""The request message for + [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.UpdateTestCase]. + + Attributes: + test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): + Required. The test case to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to specify which fields should be + updated. The + [``creationTime``][google.cloud.dialogflow.cx.v3beta1.TestCase.creation_time] + and + [``lastTestResult``][google.cloud.dialogflow.cx.v3beta1.TestCase.last_test_result] + cannot be updated. + """ + + test_case = proto.Field( + proto.MESSAGE, + number=1, + message='TestCase', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetTestCaseRequest(proto.Message): + r"""The request message for + [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCase]. + + Attributes: + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class RunTestCaseRequest(proto.Message): + r"""The request message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. + + Attributes: + name (str): + Required. Format of test case name to run: + ``projects//locations/ /agents//testCases/``. + environment (str): + Optional. Environment name. If not set, draft environment is + assumed. Format: + ``projects//locations//agents//environments/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.STRING, + number=2, + ) + + +class RunTestCaseResponse(proto.Message): + r"""The response message for + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. + + Attributes: + result (google.cloud.dialogflowcx_v3beta1.types.TestCaseResult): + The result. + """ + + result = proto.Field( + proto.MESSAGE, + number=2, + message='TestCaseResult', + ) + + +class RunTestCaseMetadata(proto.Message): + r"""Metadata returned for the + [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase] + long running operation. + """ + + +class BatchRunTestCasesRequest(proto.Message): + r"""The request message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. + + Attributes: + parent (str): + Required. Agent name. Format: + ``projects//locations//agents/ ``. + environment (str): + Optional. If not set, draft environment is assumed. Format: + ``projects//locations//agents//environments/``. + test_cases (Sequence[str]): + Required. Format: + ``projects//locations//agents//testCases/``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + environment = proto.Field( + proto.STRING, + number=2, + ) + test_cases = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class BatchRunTestCasesResponse(proto.Message): + r"""The response message for + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. + + Attributes: + results (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestCaseResult]): + The test case results. The detailed [conversation + turns][google.cloud.dialogflow.cx.v3beta1.TestCaseResult.conversation_turns] + are empty in this response. + """ + + results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TestCaseResult', + ) + + +class BatchRunTestCasesMetadata(proto.Message): + r"""Metadata returned for the + [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases] + long running operation. + + Attributes: + errors (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestError]): + The test errors. + """ + + errors = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TestError', + ) + + +class TestError(proto.Message): + r"""Error info for running a test. + Attributes: + test_case (str): + The test case resource name. + status (google.rpc.status_pb2.Status): + The status associated with the test. + test_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp when the test was completed. + """ + + test_case = proto.Field( + proto.STRING, + number=1, + ) + status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + test_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class ImportTestCasesRequest(proto.Message): + r"""The request message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. + + Attributes: + parent (str): + Required. The agent to import test cases to. Format: + ``projects//locations//agents/``. + gcs_uri (str): + The `Google Cloud + Storage `__ URI to + import test cases from. The format of this URI must be + ``gs:///``. + content (bytes): + Uncompressed raw byte content for test cases. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + gcs_uri = proto.Field( + proto.STRING, + number=2, + oneof='source', + ) + content = proto.Field( + proto.BYTES, + number=3, + oneof='source', + ) + + +class ImportTestCasesResponse(proto.Message): + r"""The response message for + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. + + Attributes: + names (Sequence[str]): + The unique identifiers of the new test cases. Format: + ``projects//locations//agents//testCases/``. + """ + + names = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class ImportTestCasesMetadata(proto.Message): + r"""Metadata returned for the + [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases] + long running operation. + + Attributes: + errors (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestCaseError]): + Errors for failed test cases. + """ + + errors = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TestCaseError', + ) + + +class TestCaseError(proto.Message): + r"""Error info for importing a test. + Attributes: + test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): + The test case. + status (google.rpc.status_pb2.Status): + The status associated with the test case. + """ + + test_case = proto.Field( + proto.MESSAGE, + number=1, + message='TestCase', + ) + status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + +class ExportTestCasesRequest(proto.Message): + r"""The request message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. + + Attributes: + parent (str): + Required. The agent where to export test cases from. Format: + ``projects//locations//agents/``. + gcs_uri (str): + The `Google Cloud + Storage `__ URI to + export the test cases to. The format of this URI must be + ``gs:///``. If unspecified, the + serialized test cases is returned inline. + data_format (google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest.DataFormat): + The data format of the exported test cases. If not + specified, ``BLOB`` is assumed. + filter (str): + The filter expression used to filter exported test cases, + see `API Filtering `__. The expression + is case insensitive and supports the following syntax: + + name = [OR name = ] ... + + For example: + + - "name = t1 OR name = t2" matches the test case with the + exact resource name "t1" or "t2". + """ + class DataFormat(proto.Enum): + r"""Data format of the exported test cases.""" + DATA_FORMAT_UNSPECIFIED = 0 + BLOB = 1 + JSON = 2 + + parent = proto.Field( + proto.STRING, + number=1, + ) + gcs_uri = proto.Field( + proto.STRING, + number=2, + oneof='destination', + ) + data_format = proto.Field( + proto.ENUM, + number=3, + enum=DataFormat, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ExportTestCasesResponse(proto.Message): + r"""The response message for + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. + + Attributes: + gcs_uri (str): + The URI to a file containing the exported test cases. This + field is populated only if ``gcs_uri`` is specified in + [ExportTestCasesRequest][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesRequest]. + content (bytes): + Uncompressed raw byte content for test cases. + """ + + gcs_uri = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + content = proto.Field( + proto.BYTES, + number=2, + oneof='destination', + ) + + +class ExportTestCasesMetadata(proto.Message): + r"""Metadata returned for the + [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases] + long running operation. + """ + + +class ListTestCaseResultsRequest(proto.Message): + r"""The request message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. + + Attributes: + parent (str): + Required. The test case to list results for. Format: + ``projects//locations//agents// testCases/``. + Specify a ``-`` as a wildcard for TestCase ID to list + results across multiple test cases. + 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. + filter (str): + The filter expression used to filter test case results. See + `API Filtering `__. + + The expression is case insensitive. Only 'AND' is supported + for logical operators. The supported syntax is listed below + in detail: + + [AND ] ... [AND latest] + + The supported fields and operators are: field operator + ``environment`` ``=``, ``IN`` (Use value ``draft`` for draft + environment) ``test_time`` ``>``, ``<`` + + ``latest`` only returns the latest test result in all + results for each test case. + + Examples: + + - "environment=draft AND latest" matches the latest test + result for each test case in the draft environment. + - "environment IN (e1,e2)" matches any test case results + with an environment resource name of either "e1" or "e2". + - "test_time > 1602540713" matches any test case results + with test time later than a unix timestamp in seconds + 1602540713. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + + +class ListTestCaseResultsResponse(proto.Message): + r"""The response message for + [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. + + Attributes: + test_case_results (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestCaseResult]): + The list of test case results. + 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 + + test_case_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TestCaseResult', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTestCaseResultRequest(proto.Message): + r"""The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCaseResult]. + + Attributes: + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py new file mode 100644 index 00000000..f176ed4c --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py @@ -0,0 +1,307 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import page +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'TransitionRouteGroup', + 'ListTransitionRouteGroupsRequest', + 'ListTransitionRouteGroupsResponse', + 'GetTransitionRouteGroupRequest', + 'CreateTransitionRouteGroupRequest', + 'UpdateTransitionRouteGroupRequest', + 'DeleteTransitionRouteGroupRequest', + }, +) + + +class TransitionRouteGroup(proto.Message): + r"""An TransitionRouteGroup represents a group of + [``TransitionRoutes``][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] + to be used by a [Page][google.cloud.dialogflow.cx.v3beta1.Page]. + + Attributes: + name (str): + The unique identifier of the transition route group. + [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.CreateTransitionRouteGroup] + populates the name automatically. Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + display_name (str): + Required. The human-readable name of the transition route + group, unique within the + [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. The + display name can be no longer than 30 characters. + transition_routes (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRoute]): + Transition routes associated with the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + transition_routes = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=page.TransitionRoute, + ) + + +class ListTransitionRouteGroupsRequest(proto.Message): + r"""The request message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. + + Attributes: + parent (str): + Required. The flow to list all transition route groups for. + Format: + ``projects//locations//agents//flows/``. + 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. + language_code (str): + The language to list transition route groups for. The + following fields are language dependent: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + language_code = proto.Field( + proto.STRING, + number=4, + ) + + +class ListTransitionRouteGroupsResponse(proto.Message): + r"""The response message for + [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. + + Attributes: + transition_route_groups (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup]): + The list of transition route groups. There will be a maximum + number of items returned based on the page_size field in the + request. The list may in some cases be empty or contain + fewer entries than page_size even if this isn't the last + page. + 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 + + transition_route_groups = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TransitionRouteGroup', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTransitionRouteGroupRequest(proto.Message): + r"""The request message for + [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.GetTransitionRouteGroup]. + + Attributes: + name (str): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. + Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + language_code (str): + The language to retrieve the transition route group for. The + following fields are language dependent: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + language_code = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateTransitionRouteGroupRequest(proto.Message): + r"""The request message for + [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.CreateTransitionRouteGroup]. + + Attributes: + parent (str): + Required. The flow to create an + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + for. Format: + ``projects//locations//agents//flows/``. + transition_route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): + Required. The transition route group to + create. + language_code (str): + The language of the following fields in + ``TransitionRouteGroup``: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + transition_route_group = proto.Field( + proto.MESSAGE, + number=2, + message='TransitionRouteGroup', + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateTransitionRouteGroupRequest(proto.Message): + r"""The request message for + [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.UpdateTransitionRouteGroup]. + + Attributes: + transition_route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): + Required. The transition route group to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + language_code (str): + The language of the following fields in + ``TransitionRouteGroup``: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` + + If not specified, the agent's default language is used. + `Many + languages `__ + are supported. Note: languages must be enabled in the agent + before they can be used. + """ + + transition_route_group = proto.Field( + proto.MESSAGE, + number=1, + message='TransitionRouteGroup', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + language_code = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteTransitionRouteGroupRequest(proto.Message): + r"""The request message for + [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.DeleteTransitionRouteGroup]. + + Attributes: + name (str): + Required. The name of the + [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] + to delete. Format: + ``projects//locations//agents//flows//transitionRouteGroups/``. + force (bool): + This field has no effect for transition route group that no + page is using. If the transition route group is referenced + by any page: + + - If ``force`` is set to false, an error will be returned + with message indicating pages that reference the + transition route group. + - If ``force`` is set to true, Dialogflow will remove the + transition route group, as well as any reference to it. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/validation_message.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/validation_message.py new file mode 100644 index 00000000..73c26538 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/validation_message.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cx.v3beta1', + manifest={ + 'ValidationMessage', + 'ResourceName', + }, +) + + +class ValidationMessage(proto.Message): + r"""Agent/flow validation message. + Attributes: + resource_type (google.cloud.dialogflowcx_v3beta1.types.ValidationMessage.ResourceType): + The type of the resources where the message + is found. + resources (Sequence[str]): + The names of the resources where the message + is found. + resource_names (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResourceName]): + The resource names of the resources where the + message is found. + severity (google.cloud.dialogflowcx_v3beta1.types.ValidationMessage.Severity): + Indicates the severity of the message. + detail (str): + The message detail. + """ + class ResourceType(proto.Enum): + r"""Resource types.""" + RESOURCE_TYPE_UNSPECIFIED = 0 + AGENT = 1 + INTENT = 2 + INTENT_TRAINING_PHRASE = 8 + INTENT_PARAMETER = 9 + INTENTS = 10 + INTENT_TRAINING_PHRASES = 11 + ENTITY_TYPE = 3 + ENTITY_TYPES = 12 + WEBHOOK = 4 + FLOW = 5 + PAGE = 6 + PAGES = 13 + TRANSITION_ROUTE_GROUP = 7 + + class Severity(proto.Enum): + r"""Severity level.""" + SEVERITY_UNSPECIFIED = 0 + INFO = 1 + WARNING = 2 + ERROR = 3 + + resource_type = proto.Field( + proto.ENUM, + number=1, + enum=ResourceType, + ) + resources = proto.RepeatedField( + proto.STRING, + number=2, + ) + resource_names = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ResourceName', + ) + severity = proto.Field( + proto.ENUM, + number=3, + enum=Severity, + ) + detail = proto.Field( + proto.STRING, + number=4, + ) + + +class ResourceName(proto.Message): + r"""Resource name and display name. + Attributes: + name (str): + Name. + display_name (str): + Display name. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/version.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/version.py new file mode 100644 index 00000000..a49ea58d --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/version.py @@ -0,0 +1,295 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import flow +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'CreateVersionOperationMetadata', + 'Version', + 'ListVersionsRequest', + 'ListVersionsResponse', + 'GetVersionRequest', + 'CreateVersionRequest', + 'UpdateVersionRequest', + 'DeleteVersionRequest', + 'LoadVersionRequest', + }, +) + + +class CreateVersionOperationMetadata(proto.Message): + r"""Metadata associated with the long running operation for + [Versions.CreateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.CreateVersion]. + + Attributes: + version (str): + Name of the created version. Format: + ``projects//locations//agents//flows//versions/``. + """ + + version = proto.Field( + proto.STRING, + number=1, + ) + + +class Version(proto.Message): + r"""Represents a version of a flow. + Attributes: + name (str): + Format: projects//locations//agents//flows//versions/. + Version ID is a self-increasing number generated + by Dialogflow upon version creation. + display_name (str): + Required. The human-readable name of the + version. Limit of 64 characters. + description (str): + The description of the version. The maximum + length is 500 characters. If exceeded, the + request is rejected. + nlu_settings (google.cloud.dialogflowcx_v3beta1.types.NluSettings): + Output only. The NLU settings of the flow at + version creation. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time of the version. + state (google.cloud.dialogflowcx_v3beta1.types.Version.State): + Output only. The state of this version. This + field is read-only and cannot be set by create + and update methods. + """ + class State(proto.Enum): + r"""The state of the version.""" + STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + nlu_settings = proto.Field( + proto.MESSAGE, + number=4, + message=flow.NluSettings, + ) + create_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + state = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + + +class ListVersionsRequest(proto.Message): + r"""The request message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.Versions.ListVersions]. + + Attributes: + parent (str): + Required. The + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to list all + versions for. Format: + ``projects//locations//agents//flows/``. + page_size (int): + The maximum number of items to return in a + single page. By default 20 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 ListVersionsResponse(proto.Message): + r"""The response message for + [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.Versions.ListVersions]. + + Attributes: + versions (Sequence[google.cloud.dialogflowcx_v3beta1.types.Version]): + A list of versions. There will be a maximum number of items + returned based on the page_size field in the request. The + list may in some cases be empty or contain fewer entries + than page_size even if this isn't the last page. + 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.cx.v3beta1.Versions.GetVersion]. + + Attributes: + name (str): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3beta1.Version]. + Format: + ``projects//locations//agents//flows//versions/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateVersionRequest(proto.Message): + r"""The request message for + [Versions.CreateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.CreateVersion]. + + Attributes: + parent (str): + Required. The + [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to create an + [Version][google.cloud.dialogflow.cx.v3beta1.Version] for. + Format: + ``projects//locations//agents//flows/``. + version (google.cloud.dialogflowcx_v3beta1.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.cx.v3beta1.Versions.UpdateVersion]. + + Attributes: + version (google.cloud.dialogflowcx_v3beta1.types.Version): + Required. The version to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields get updated. + Currently only ``description`` and ``display_name`` can be + 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.cx.v3beta1.Versions.DeleteVersion]. + + Attributes: + name (str): + Required. The name of the + [Version][google.cloud.dialogflow.cx.v3beta1.Version] to + delete. Format: + ``projects//locations//agents//flows//versions/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class LoadVersionRequest(proto.Message): + r"""The request message for + [Versions.LoadVersion][google.cloud.dialogflow.cx.v3beta1.Versions.LoadVersion]. + + Attributes: + name (str): + Required. The + [Version][google.cloud.dialogflow.cx.v3beta1.Version] to be + loaded to draft flow. Format: + ``projects//locations//agents//flows//versions/``. + allow_override_agent_resources (bool): + This field is used to prevent accidental overwrite of other + agent resources, which can potentially impact other flow's + behavior. If ``allow_override_agent_resources`` is false, + conflicted agent-level resources will not be overridden + (i.e. intents, entities, webhooks). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + allow_override_agent_resources = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/webhook.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/webhook.py new file mode 100644 index 00000000..88209a31 --- /dev/null +++ b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/webhook.py @@ -0,0 +1,793 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import response_message +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.dialogflow.cx.v3beta1', + manifest={ + 'Webhook', + 'ListWebhooksRequest', + 'ListWebhooksResponse', + 'GetWebhookRequest', + 'CreateWebhookRequest', + 'UpdateWebhookRequest', + 'DeleteWebhookRequest', + 'WebhookRequest', + 'WebhookResponse', + 'PageInfo', + 'SessionInfo', + }, +) + + +class Webhook(proto.Message): + r"""Webhooks host the developer's business logic. During a + session, webhooks allow the developer to use the data extracted + by Dialogflow's natural language processing to generate dynamic + responses, validate collected data, or trigger actions on the + backend. + + Attributes: + name (str): + The unique identifier of the webhook. Required for the + [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook] + method. + [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook] + populates the name automatically. Format: + ``projects//locations//agents//webhooks/``. + display_name (str): + Required. The human-readable name of the + webhook, unique within the agent. + generic_web_service (google.cloud.dialogflowcx_v3beta1.types.Webhook.GenericWebService): + Configuration for a generic web service. + service_directory (google.cloud.dialogflowcx_v3beta1.types.Webhook.ServiceDirectoryConfig): + Configuration for a `Service + Directory `__ + service. + timeout (google.protobuf.duration_pb2.Duration): + Webhook execution timeout. Execution is + considered failed if Dialogflow doesn't receive + a response from webhook at the end of the + timeout period. Defaults to 5 seconds, maximum + allowed timeout is 30 seconds. + disabled (bool): + Indicates whether the webhook is disabled. + """ + + class GenericWebService(proto.Message): + r"""Represents configuration for a generic web service. + Attributes: + uri (str): + Required. The webhook 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.dialogflowcx_v3beta1.types.Webhook.GenericWebService.RequestHeadersEntry]): + The HTTP request headers to send together + with webhook requests. + """ + + 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, + ) + + class ServiceDirectoryConfig(proto.Message): + r"""Represents configuration for a `Service + Directory `__ service. + + Attributes: + service (str): + Required. The name of `Service + Directory `__ + service. Format: + ``projects//locations//namespaces//services/``. + ``Location ID`` of the service directory must be the same as + the location of the agent. + generic_web_service (google.cloud.dialogflowcx_v3beta1.types.Webhook.GenericWebService): + Generic Service configuration of this + webhook. + """ + + service = proto.Field( + proto.STRING, + number=1, + ) + generic_web_service = proto.Field( + proto.MESSAGE, + number=2, + message='Webhook.GenericWebService', + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + generic_web_service = proto.Field( + proto.MESSAGE, + number=4, + oneof='webhook', + message=GenericWebService, + ) + service_directory = proto.Field( + proto.MESSAGE, + number=7, + oneof='webhook', + message=ServiceDirectoryConfig, + ) + timeout = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + disabled = proto.Field( + proto.BOOL, + number=5, + ) + + +class ListWebhooksRequest(proto.Message): + r"""The request message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. + + Attributes: + parent (str): + Required. The agent to list all webhooks for. Format: + ``projects//locations//agents/``. + 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 ListWebhooksResponse(proto.Message): + r"""The response message for + [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. + + Attributes: + webhooks (Sequence[google.cloud.dialogflowcx_v3beta1.types.Webhook]): + The list of webhooks. 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 + + webhooks = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Webhook', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class GetWebhookRequest(proto.Message): + r"""The request message for + [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.GetWebhook]. + + Attributes: + name (str): + Required. The name of the webhook. Format: + ``projects//locations//agents//webhooks/``. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateWebhookRequest(proto.Message): + r"""The request message for + [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook]. + + Attributes: + parent (str): + Required. The agent to create a webhook for. Format: + ``projects//locations//agents/``. + webhook (google.cloud.dialogflowcx_v3beta1.types.Webhook): + Required. The webhook to create. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + webhook = proto.Field( + proto.MESSAGE, + number=2, + message='Webhook', + ) + + +class UpdateWebhookRequest(proto.Message): + r"""The request message for + [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook]. + + Attributes: + webhook (google.cloud.dialogflowcx_v3beta1.types.Webhook): + Required. The webhook to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The mask to control which fields get updated. + If the mask is not present, all fields will be + updated. + """ + + webhook = proto.Field( + proto.MESSAGE, + number=1, + message='Webhook', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteWebhookRequest(proto.Message): + r"""The request message for + [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.DeleteWebhook]. + + Attributes: + name (str): + Required. The name of the webhook to delete. Format: + ``projects//locations//agents//webhooks/``. + force (bool): + This field has no effect for webhook not being used. For + webhooks that are used by pages/flows/transition route + groups: + + - If ``force`` is set to false, an error will be returned + with message indicating the referenced resources. + - If ``force`` is set to true, Dialogflow will remove the + webhook, as well as any references to the webhook (i.e. + [Webhook][google.cloud.dialogflow.cx.v3beta1.Fulfillment.webhook] + and + [tag][google.cloud.dialogflow.cx.v3beta1.Fulfillment.tag]in + fulfillments that point to this webhook will be removed). + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + force = proto.Field( + proto.BOOL, + number=2, + ) + + +class WebhookRequest(proto.Message): + r"""The request message for a webhook call. The request is sent + as a JSON object and the field names will be presented in camel + cases. + + Attributes: + detect_intent_response_id (str): + Always present. The unique identifier of the + [DetectIntentResponse][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse] + that will be returned to the API caller. + text (str): + If [natural language + text][google.cloud.dialogflow.cx.v3beta1.TextInput] was + provided as input, this field will contain a copy of the + text. + trigger_intent (str): + If an + [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was + provided as input, this field will contain a copy of the + intent identifier. Format: + ``projects//locations//agents//intents/``. + transcript (str): + If [natural language speech + audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was + provided as input, this field will contain the transcript + for the audio. + trigger_event (str): + If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] + was provided as input, this field will contain the name of + the event. + language_code (str): + The language code specified in the [original + request][QueryInput.language_code]. + fulfillment_info (google.cloud.dialogflowcx_v3beta1.types.WebhookRequest.FulfillmentInfo): + Always present. Information about the + fulfillment that triggered this webhook call. + intent_info (google.cloud.dialogflowcx_v3beta1.types.WebhookRequest.IntentInfo): + Information about the last matched intent. + page_info (google.cloud.dialogflowcx_v3beta1.types.PageInfo): + Information about page status. + session_info (google.cloud.dialogflowcx_v3beta1.types.SessionInfo): + Information about session status. + messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage]): + The list of rich message responses to present to the user. + Webhook can choose to append or replace this list in + [WebhookResponse.fulfillment_response][google.cloud.dialogflow.cx.v3beta1.WebhookResponse.fulfillment_response]; + payload (google.protobuf.struct_pb2.Struct): + Custom data set in + [QueryParameters.payload][google.cloud.dialogflow.cx.v3beta1.QueryParameters.payload]. + sentiment_analysis_result (google.cloud.dialogflowcx_v3beta1.types.WebhookRequest.SentimentAnalysisResult): + The sentiment analysis result of the current + user request. The field is filled when sentiment + analysis is configured to be enabled for the + request. + """ + + class FulfillmentInfo(proto.Message): + r"""Represents fulfillment information communicated to the + webhook. + + Attributes: + tag (str): + Always present. The tag used to identify + which fulfillment is being called. + """ + + tag = proto.Field( + proto.STRING, + number=1, + ) + + class IntentInfo(proto.Message): + r"""Represents intent information communicated to the webhook. + Attributes: + last_matched_intent (str): + Always present. The unique identifier of the last matched + [intent][google.cloud.dialogflow.cx.v3beta1.Intent]. Format: + ``projects//locations//agents//intents/``. + display_name (str): + Always present. The display name of the last matched + [intent][google.cloud.dialogflow.cx.v3beta1.Intent]. + parameters (Sequence[google.cloud.dialogflowcx_v3beta1.types.WebhookRequest.IntentInfo.ParametersEntry]): + Parameters identified as a result of intent + matching. This is a map of the name of the + identified parameter to the value of the + parameter identified from the user's utterance. + All parameters defined in the matched intent + that are identified will be surfaced here. + confidence (float): + The confidence of the matched intent. Values + range from 0.0 (completely uncertain) to 1.0 + (completely certain). + """ + + class IntentParameterValue(proto.Message): + r"""Represents a value for an intent parameter. + Attributes: + original_value (str): + Always present. Original text value extracted + from user utterance. + resolved_value (google.protobuf.struct_pb2.Value): + Always present. Structured value for the + parameter extracted from user utterance. + """ + + original_value = proto.Field( + proto.STRING, + number=1, + ) + resolved_value = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + last_matched_intent = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=3, + ) + parameters = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message='WebhookRequest.IntentInfo.IntentParameterValue', + ) + confidence = proto.Field( + proto.FLOAT, + number=4, + ) + + class SentimentAnalysisResult(proto.Message): + r"""Represents the result of sentiment analysis. + 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, + ) + + detect_intent_response_id = proto.Field( + proto.STRING, + number=1, + ) + text = proto.Field( + proto.STRING, + number=10, + oneof='query', + ) + trigger_intent = proto.Field( + proto.STRING, + number=11, + oneof='query', + ) + transcript = proto.Field( + proto.STRING, + number=12, + oneof='query', + ) + trigger_event = proto.Field( + proto.STRING, + number=14, + oneof='query', + ) + language_code = proto.Field( + proto.STRING, + number=15, + ) + fulfillment_info = proto.Field( + proto.MESSAGE, + number=6, + message=FulfillmentInfo, + ) + intent_info = proto.Field( + proto.MESSAGE, + number=3, + message=IntentInfo, + ) + page_info = proto.Field( + proto.MESSAGE, + number=4, + message='PageInfo', + ) + session_info = proto.Field( + proto.MESSAGE, + number=5, + message='SessionInfo', + ) + messages = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=response_message.ResponseMessage, + ) + payload = proto.Field( + proto.MESSAGE, + number=8, + message=struct_pb2.Struct, + ) + sentiment_analysis_result = proto.Field( + proto.MESSAGE, + number=9, + message=SentimentAnalysisResult, + ) + + +class WebhookResponse(proto.Message): + r"""The response message for a webhook call. + Attributes: + fulfillment_response (google.cloud.dialogflowcx_v3beta1.types.WebhookResponse.FulfillmentResponse): + The fulfillment response to send to the user. + This field can be omitted by the webhook if it + does not intend to send any response to the + user. + page_info (google.cloud.dialogflowcx_v3beta1.types.PageInfo): + Information about page status. This field can + be omitted by the webhook if it does not intend + to modify page status. + session_info (google.cloud.dialogflowcx_v3beta1.types.SessionInfo): + Information about session status. This field + can be omitted by the webhook if it does not + intend to modify session status. + payload (google.protobuf.struct_pb2.Struct): + Value to append directly to + [QueryResult.webhook_payloads][google.cloud.dialogflow.cx.v3beta1.QueryResult.webhook_payloads]. + target_page (str): + The target page to transition to. Format: + ``projects//locations//agents//flows//pages/``. + target_flow (str): + The target flow to transition to. Format: + ``projects//locations//agents//flows/``. + """ + + class FulfillmentResponse(proto.Message): + r"""Represents a fulfillment response to the user. + Attributes: + messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage]): + The list of rich message responses to present + to the user. + merge_behavior (google.cloud.dialogflowcx_v3beta1.types.WebhookResponse.FulfillmentResponse.MergeBehavior): + Merge behavior for ``messages``. + """ + class MergeBehavior(proto.Enum): + r"""Defines merge behavior for ``messages``.""" + MERGE_BEHAVIOR_UNSPECIFIED = 0 + APPEND = 1 + REPLACE = 2 + + messages = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=response_message.ResponseMessage, + ) + merge_behavior = proto.Field( + proto.ENUM, + number=2, + enum='WebhookResponse.FulfillmentResponse.MergeBehavior', + ) + + fulfillment_response = proto.Field( + proto.MESSAGE, + number=1, + message=FulfillmentResponse, + ) + page_info = proto.Field( + proto.MESSAGE, + number=2, + message='PageInfo', + ) + session_info = proto.Field( + proto.MESSAGE, + number=3, + message='SessionInfo', + ) + payload = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + target_page = proto.Field( + proto.STRING, + number=5, + oneof='transition', + ) + target_flow = proto.Field( + proto.STRING, + number=6, + oneof='transition', + ) + + +class PageInfo(proto.Message): + r"""Represents page information communicated to and from the + webhook. + + Attributes: + current_page (str): + Always present for + [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. + Ignored for + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + The unique identifier of the current page. Format: + ``projects//locations//agents//flows//pages/``. + form_info (google.cloud.dialogflowcx_v3beta1.types.PageInfo.FormInfo): + Optional for both + [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] + and + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + Information about the form. + """ + + class FormInfo(proto.Message): + r"""Represents form information. + Attributes: + parameter_info (Sequence[google.cloud.dialogflowcx_v3beta1.types.PageInfo.FormInfo.ParameterInfo]): + Optional for both + [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] + and + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + The parameters contained in the form. Note that the webhook + cannot add or remove any form parameter. + """ + + class ParameterInfo(proto.Message): + r"""Represents parameter information. + Attributes: + display_name (str): + Always present for + [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. + Required for + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + The human-readable name of the parameter, unique within the + form. This field cannot be modified by the webhook. + required (bool): + Optional for both + [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] + and + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + Indicates whether the parameter is required. Optional + parameters will not trigger prompts; however, they are + filled if the user specifies them. Required parameters must + be filled before form filling concludes. + state (google.cloud.dialogflowcx_v3beta1.types.PageInfo.FormInfo.ParameterInfo.ParameterState): + Always present for + [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. + Required for + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + The state of the parameter. This field can be set to + [INVALID][google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo.ParameterInfo.ParameterState.INVALID] + by the webhook to invalidate the parameter; other values set + by the webhook will be ignored. + value (google.protobuf.struct_pb2.Value): + Optional for both + [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] + and + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + The value of the parameter. This field can be set by the + webhook to change the parameter value. + just_collected (bool): + Optional for + [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. + Ignored for + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + Indicates if the parameter value was just collected on the + last conversation turn. + """ + class ParameterState(proto.Enum): + r"""Represents the state of a parameter.""" + PARAMETER_STATE_UNSPECIFIED = 0 + EMPTY = 1 + INVALID = 2 + FILLED = 3 + + display_name = proto.Field( + proto.STRING, + number=1, + ) + required = proto.Field( + proto.BOOL, + number=2, + ) + state = proto.Field( + proto.ENUM, + number=3, + enum='PageInfo.FormInfo.ParameterInfo.ParameterState', + ) + value = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Value, + ) + just_collected = proto.Field( + proto.BOOL, + number=5, + ) + + parameter_info = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='PageInfo.FormInfo.ParameterInfo', + ) + + current_page = proto.Field( + proto.STRING, + number=1, + ) + form_info = proto.Field( + proto.MESSAGE, + number=3, + message=FormInfo, + ) + + +class SessionInfo(proto.Message): + r"""Represents session information communicated to and from the + webhook. + + Attributes: + session (str): + Always present for + [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. + Ignored for + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + The unique identifier of the + [session][google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest.session]. + This field can be used by the webhook to identify a session. + Format: + ``projects//locations//agents//sessions/`` + or + ``projects//locations//agents//environments//sessions/`` + if environment is specified. + parameters (Sequence[google.cloud.dialogflowcx_v3beta1.types.SessionInfo.ParametersEntry]): + Optional for + [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. + Optional for + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + All parameters collected from forms and intents during the + session. Parameters can be created, updated, or removed by + the webhook. To remove a parameter from the session, the + webhook should explicitly set the parameter value to null in + [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. + The map is keyed by parameters' display names. + """ + + session = proto.Field( + proto.STRING, + number=1, + ) + parameters = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/mypy.ini b/owl-bot-staging/v3beta1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v3beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v3beta1/noxfile.py b/owl-bot-staging/v3beta1/noxfile.py new file mode 100644 index 00000000..a1f5d979 --- /dev/null +++ b/owl-bot-staging/v3beta1/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/dialogflowcx_v3beta1/', + '--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/v3beta1/scripts/fixup_dialogflowcx_v3beta1_keywords.py b/owl-bot-staging/v3beta1/scripts/fixup_dialogflowcx_v3beta1_keywords.py new file mode 100644 index 00000000..a1485d95 --- /dev/null +++ b/owl-bot-staging/v3beta1/scripts/fixup_dialogflowcx_v3beta1_keywords.py @@ -0,0 +1,266 @@ +#! /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 dialogflowcxCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_delete_test_cases': ('parent', 'names', ), + 'batch_run_test_cases': ('parent', 'test_cases', 'environment', ), + 'calculate_coverage': ('agent', 'type_', ), + 'create_agent': ('parent', 'agent', ), + 'create_entity_type': ('parent', 'entity_type', 'language_code', ), + 'create_environment': ('parent', 'environment', ), + 'create_experiment': ('parent', 'experiment', ), + 'create_flow': ('parent', 'flow', 'language_code', ), + 'create_intent': ('parent', 'intent', 'language_code', ), + 'create_page': ('parent', 'page', 'language_code', ), + 'create_security_settings': ('parent', 'security_settings', ), + 'create_session_entity_type': ('parent', 'session_entity_type', ), + 'create_test_case': ('parent', 'test_case', ), + 'create_transition_route_group': ('parent', 'transition_route_group', 'language_code', ), + 'create_version': ('parent', 'version', ), + 'create_webhook': ('parent', 'webhook', ), + 'delete_agent': ('name', ), + 'delete_entity_type': ('name', 'force', ), + 'delete_environment': ('name', ), + 'delete_experiment': ('name', ), + 'delete_flow': ('name', 'force', ), + 'delete_intent': ('name', ), + 'delete_page': ('name', 'force', ), + 'delete_security_settings': ('name', ), + 'delete_session_entity_type': ('name', ), + 'delete_transition_route_group': ('name', 'force', ), + 'delete_version': ('name', ), + 'delete_webhook': ('name', 'force', ), + 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', ), + 'export_agent': ('name', 'agent_uri', 'environment', ), + 'export_flow': ('name', 'flow_uri', 'include_referenced_flows', ), + 'export_test_cases': ('parent', 'gcs_uri', 'data_format', 'filter', ), + 'fulfill_intent': ('match_intent_request', 'match', 'output_audio_config', ), + 'get_agent': ('name', ), + 'get_agent_validation_result': ('name', 'language_code', ), + 'get_entity_type': ('name', 'language_code', ), + 'get_environment': ('name', ), + 'get_experiment': ('name', ), + 'get_flow': ('name', 'language_code', ), + 'get_flow_validation_result': ('name', 'language_code', ), + 'get_intent': ('name', 'language_code', ), + 'get_page': ('name', 'language_code', ), + 'get_security_settings': ('name', ), + 'get_session_entity_type': ('name', ), + 'get_test_case': ('name', ), + 'get_test_case_result': ('name', ), + 'get_transition_route_group': ('name', 'language_code', ), + 'get_version': ('name', ), + 'get_webhook': ('name', ), + 'import_flow': ('parent', 'flow_uri', 'flow_content', 'import_option', ), + 'import_test_cases': ('parent', 'gcs_uri', 'content', ), + 'list_agents': ('parent', 'page_size', 'page_token', ), + 'list_continuous_test_results': ('parent', 'page_size', 'page_token', ), + 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_experiments': ('parent', 'page_size', 'page_token', ), + 'list_flows': ('parent', 'page_size', 'page_token', 'language_code', ), + 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), + 'list_pages': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_security_settings': ('parent', 'page_size', 'page_token', ), + 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), + 'list_test_case_results': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_test_cases': ('parent', 'page_size', 'page_token', 'view', ), + 'list_transition_route_groups': ('parent', 'page_size', 'page_token', 'language_code', ), + 'list_versions': ('parent', 'page_size', 'page_token', ), + 'list_webhooks': ('parent', 'page_size', 'page_token', ), + 'load_version': ('name', 'allow_override_agent_resources', ), + 'lookup_environment_history': ('name', 'page_size', 'page_token', ), + 'match_intent': ('session', 'query_input', 'query_params', ), + 'restore_agent': ('name', 'agent_uri', 'agent_content', 'restore_option', ), + 'run_continuous_test': ('environment', ), + 'run_test_case': ('name', 'environment', ), + 'start_experiment': ('name', ), + 'stop_experiment': ('name', ), + 'streaming_detect_intent': ('query_input', 'session', 'query_params', 'output_audio_config', ), + 'train_flow': ('name', ), + 'update_agent': ('agent', 'update_mask', ), + 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), + 'update_environment': ('environment', 'update_mask', ), + 'update_experiment': ('experiment', 'update_mask', ), + 'update_flow': ('flow', 'update_mask', 'language_code', ), + 'update_intent': ('intent', 'language_code', 'update_mask', ), + 'update_page': ('page', 'language_code', 'update_mask', ), + 'update_security_settings': ('security_settings', 'update_mask', ), + 'update_session_entity_type': ('session_entity_type', 'update_mask', ), + 'update_test_case': ('test_case', 'update_mask', ), + 'update_transition_route_group': ('transition_route_group', 'update_mask', 'language_code', ), + 'update_version': ('version', 'update_mask', ), + 'update_webhook': ('webhook', 'update_mask', ), + 'validate_agent': ('name', 'language_code', ), + 'validate_flow': ('name', 'language_code', ), + } + + 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=dialogflowcxCallTransformer(), +): + """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 dialogflowcx 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/v3beta1/setup.py b/owl-bot-staging/v3beta1/setup.py new file mode 100644 index 00000000..18e33869 --- /dev/null +++ b/owl-bot-staging/v3beta1/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-dialogflowcx', + 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/v3beta1/tests/__init__.py b/owl-bot-staging/v3beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v3beta1/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/v3beta1/tests/unit/__init__.py b/owl-bot-staging/v3beta1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v3beta1/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/v3beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v3beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v3beta1/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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/__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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py new file mode 100644 index 00000000..f30d1f1b --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py @@ -0,0 +1,3312 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.agents import AgentsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.agents import AgentsClient +from google.cloud.dialogflowcx_v3beta1.services.agents import pagers +from google.cloud.dialogflowcx_v3beta1.services.agents import transports +from google.cloud.dialogflowcx_v3beta1.services.agents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.agents.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import agent +from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent +from google.cloud.dialogflowcx_v3beta1.types import flow +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3beta1.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_list_agents(transport: str = 'grpc', request_type=agent.ListAgentsRequest): + 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.list_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.ListAgentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ListAgentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_agents_from_dict(): + test_list_agents(request_type=dict) + + +def test_list_agents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agents), + '__call__') as call: + client.list_agents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ListAgentsRequest() + + +@pytest.mark.asyncio +async def test_list_agents_async(transport: str = 'grpc_asyncio', request_type=agent.ListAgentsRequest): + 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.list_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ListAgentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_agents_async_from_dict(): + await test_list_agents_async(request_type=dict) + + +def test_list_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.ListAgentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agents), + '__call__') as call: + call.return_value = agent.ListAgentsResponse() + client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_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.ListAgentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse()) + await client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_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.list_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.ListAgentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_agents( + parent='parent_value', + ) + + # Establish that the 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_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.list_agents( + agent.ListAgentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_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.list_agents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.ListAgentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_list_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.list_agents( + agent.ListAgentsRequest(), + parent='parent_value', + ) + + +def test_list_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.list_agents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.ListAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_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_list_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.list_agents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.ListAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_list_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.list_agents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.ListAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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_list_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.list_agents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token='abc', + ), + agent.ListAgentsResponse( + agents=[], + next_page_token='def', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token='ghi', + ), + agent.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_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_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( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + ) + response = client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +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( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + )) + response = await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +@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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + call.return_value = agent.Agent() + client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) + await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_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( + 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_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(), + name='name_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( + 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_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(), + name='name_value', + ) + + +def test_create_agent(transport: str = 'grpc', request_type=gcdc_agent.CreateAgentRequest): + 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.create_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + ) + response = client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.CreateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +def test_create_agent_from_dict(): + test_create_agent(request_type=dict) + + +def test_create_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agent), + '__call__') as call: + client.create_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.CreateAgentRequest() + + +@pytest.mark.asyncio +async def test_create_agent_async(transport: str = 'grpc_asyncio', request_type=gcdc_agent.CreateAgentRequest): + 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.create_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + )) + response = await client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.CreateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +@pytest.mark.asyncio +async def test_create_agent_async_from_dict(): + await test_create_agent_async(request_type=dict) + + +def test_create_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 = gcdc_agent.CreateAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_agent), + '__call__') as call: + call.return_value = gcdc_agent.Agent() + client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_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 = gcdc_agent.CreateAgentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) + await client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_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.create_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_agent( + parent='parent_value', + agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') + + +def test_create_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.create_agent( + gcdc_agent.CreateAgentRequest(), + parent='parent_value', + agent=gcdc_agent.Agent(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_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.create_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_agent( + parent='parent_value', + agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') + + +@pytest.mark.asyncio +async def test_create_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.create_agent( + gcdc_agent.CreateAgentRequest(), + parent='parent_value', + agent=gcdc_agent.Agent(name='name_value'), + ) + + +def test_update_agent(transport: str = 'grpc', request_type=gcdc_agent.UpdateAgentRequest): + 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.update_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + ) + response = client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.UpdateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +def test_update_agent_from_dict(): + test_update_agent(request_type=dict) + + +def test_update_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_agent), + '__call__') as call: + client.update_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.UpdateAgentRequest() + + +@pytest.mark.asyncio +async def test_update_agent_async(transport: str = 'grpc_asyncio', request_type=gcdc_agent.UpdateAgentRequest): + 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.update_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent( + name='name_value', + display_name='display_name_value', + default_language_code='default_language_code_value', + supported_language_codes=['supported_language_codes_value'], + time_zone='time_zone_value', + description='description_value', + avatar_uri='avatar_uri_value', + start_flow='start_flow_value', + security_settings='security_settings_value', + enable_stackdriver_logging=True, + enable_spell_correction=True, + )) + response = await client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_agent.UpdateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_agent.Agent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.default_language_code == 'default_language_code_value' + assert response.supported_language_codes == ['supported_language_codes_value'] + assert response.time_zone == 'time_zone_value' + assert response.description == 'description_value' + assert response.avatar_uri == 'avatar_uri_value' + assert response.start_flow == 'start_flow_value' + assert response.security_settings == 'security_settings_value' + assert response.enable_stackdriver_logging is True + assert response.enable_spell_correction is True + + +@pytest.mark.asyncio +async def test_update_agent_async_from_dict(): + await test_update_agent_async(request_type=dict) + + +def test_update_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 = gcdc_agent.UpdateAgentRequest() + + request.agent.name = 'agent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_agent), + '__call__') as call: + call.return_value = gcdc_agent.Agent() + client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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.name=agent.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_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 = gcdc_agent.UpdateAgentRequest() + + request.agent.name = 'agent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) + await client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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.name=agent.name/value', + ) in kw['metadata'] + + +def test_update_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.update_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_agent( + agent=gcdc_agent.Agent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].agent == gcdc_agent.Agent(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_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.update_agent( + gcdc_agent.UpdateAgentRequest(), + agent=gcdc_agent.Agent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_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.update_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_agent( + agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_agent_flattened_error_async(): + client = AgentsAsyncClient( + credentials=ga_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_agent( + gcdc_agent.UpdateAgentRequest(), + agent=gcdc_agent.Agent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__call__') as call: + call.return_value = None + client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_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( + 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_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(), + name='name_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( + 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_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(), + name='name_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_export_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_agent), + '__call__') as call: + call.return_value = 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', + 'name=name/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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restore_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_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.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_agent), + '__call__') as call: + call.return_value = 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', + 'name=name/value', + ) in kw['metadata'] + + +def test_validate_agent(transport: str = 'grpc', request_type=agent.ValidateAgentRequest): + 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.validate_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.AgentValidationResult( + name='name_value', + ) + response = client.validate_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ValidateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.AgentValidationResult) + assert response.name == 'name_value' + + +def test_validate_agent_from_dict(): + test_validate_agent(request_type=dict) + + +def test_validate_agent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_agent), + '__call__') as call: + client.validate_agent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ValidateAgentRequest() + + +@pytest.mark.asyncio +async def test_validate_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ValidateAgentRequest): + 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.validate_agent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult( + name='name_value', + )) + response = await client.validate_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.ValidateAgentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.AgentValidationResult) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_validate_agent_async_from_dict(): + await test_validate_agent_async(request_type=dict) + + +def test_validate_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.ValidateAgentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_agent), + '__call__') as call: + call.return_value = agent.AgentValidationResult() + client.validate_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_validate_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.ValidateAgentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_agent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) + await client.validate_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_agent_validation_result(transport: str = 'grpc', request_type=agent.GetAgentValidationResultRequest): + 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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.AgentValidationResult( + name='name_value', + ) + response = client.get_agent_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.AgentValidationResult) + assert response.name == 'name_value' + + +def test_get_agent_validation_result_from_dict(): + test_get_agent_validation_result(request_type=dict) + + +def test_get_agent_validation_result_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AgentsClient( + credentials=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_validation_result), + '__call__') as call: + client.get_agent_validation_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentValidationResultRequest() + + +@pytest.mark.asyncio +async def test_get_agent_validation_result_async(transport: str = 'grpc_asyncio', request_type=agent.GetAgentValidationResultRequest): + 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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult( + name='name_value', + )) + response = await client.get_agent_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == agent.GetAgentValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.AgentValidationResult) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_agent_validation_result_async_from_dict(): + await test_get_agent_validation_result_async(request_type=dict) + + +def test_get_agent_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.GetAgentValidationResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent_validation_result), + '__call__') as call: + call.return_value = agent.AgentValidationResult() + client.get_agent_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_agent_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.GetAgentValidationResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_agent_validation_result), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) + await client.get_agent_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_agent_validation_result_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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.AgentValidationResult() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_agent_validation_result( + name='name_value', + ) + + # Establish that the 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_agent_validation_result_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_validation_result( + agent.GetAgentValidationResultRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_agent_validation_result_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_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = agent.AgentValidationResult() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_agent_validation_result( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_agent_validation_result_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_validation_result( + agent.GetAgentValidationResultRequest(), + name='name_value', + ) + + +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.dialogflowcx_v3beta1.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 = ( + 'list_agents', + 'get_agent', + 'create_agent', + 'update_agent', + 'delete_agent', + 'export_agent', + 'restore_agent', + 'validate_agent', + 'get_agent_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.dialogflowcx_v3beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_agents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + 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.dialogflowcx_v3beta1.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" + location = "clam" + agent = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) + actual = AgentsClient.agent_path(project, location, agent) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + } + path = AgentsClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_agent_path(path) + assert expected == actual + +def test_agent_validation_result_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + expected = "projects/{project}/locations/{location}/agents/{agent}/validationResult".format(project=project, location=location, agent=agent, ) + actual = AgentsClient.agent_validation_result_path(project, location, agent) + assert expected == actual + + +def test_parse_agent_validation_result_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "agent": "abalone", + } + path = AgentsClient.agent_validation_result_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_agent_validation_result_path(path) + assert expected == actual + +def test_environment_path(): + project = "squid" + location = "clam" + agent = "whelk" + environment = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + actual = AgentsClient.environment_path(project, location, agent, environment) + assert expected == actual + + +def test_parse_environment_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "environment": "mussel", + } + path = AgentsClient.environment_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_environment_path(path) + assert expected == actual + +def test_flow_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + flow = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = AgentsClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "flow": "octopus", + } + path = AgentsClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_flow_path(path) + assert expected == actual + +def test_flow_validation_result_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + flow = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) + actual = AgentsClient.flow_validation_result_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_validation_result_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "flow": "abalone", + } + path = AgentsClient.flow_validation_result_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_flow_validation_result_path(path) + assert expected == actual + +def test_security_settings_path(): + project = "squid" + location = "clam" + security_settings = "whelk" + expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + actual = AgentsClient.security_settings_path(project, location, security_settings) + assert expected == actual + + +def test_parse_security_settings_path(): + expected = { + "project": "octopus", + "location": "oyster", + "security_settings": "nudibranch", + } + path = AgentsClient.security_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_security_settings_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + 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": "mussel", + } + 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 = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = AgentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + 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 = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AgentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + 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 = "squid" + expected = "projects/{project}".format(project=project, ) + actual = AgentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + 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 = "whelk" + location = "octopus" + 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": "oyster", + "location": "nudibranch", + } + 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py new file mode 100644 index 00000000..40d3eac0 --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py @@ -0,0 +1,2418 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.entity_types import EntityTypesAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.entity_types import EntityTypesClient +from google.cloud.dialogflowcx_v3beta1.services.entity_types import pagers +from google.cloud.dialogflowcx_v3beta1.services.entity_types import transports +from google.cloud.dialogflowcx_v3beta1.services.entity_types.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.entity_types.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import entity_type +from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3beta1.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', + ) + + # Establish that the 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_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', + ) + + +@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', + ) + + # Establish that 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_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', + ) + + +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, + redact=True, + ) + response = client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.GetEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +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, + redact=True, + )) + response = await client.get_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == entity_type.GetEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +@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', + ) + + # Establish that the 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_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', + ) + + +@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', + ) + + # Establish that 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_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', + ) + + +def test_create_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + redact=True, + ) + response = client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +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] == gcdc_entity_type.CreateEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_create_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + redact=True, + )) + response = await client.create_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_entity_type.EntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_entity_type( + parent='parent_value', + entity_type=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( + gcdc_entity_type.CreateEntityTypeRequest(), + parent='parent_value', + entity_type=gcdc_entity_type.EntityType(name='name_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 = gcdc_entity_type.EntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( + gcdc_entity_type.CreateEntityTypeRequest(), + parent='parent_value', + entity_type=gcdc_entity_type.EntityType(name='name_value'), + ) + + +def test_update_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + redact=True, + ) + response = client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +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] == gcdc_entity_type.UpdateEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_update_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_entity_type.EntityType( + name='name_value', + display_name='display_name_value', + kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, + auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, + enable_fuzzy_extraction=True, + redact=True, + )) + response = await client.update_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_entity_type.EntityType) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP + assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT + assert response.enable_fuzzy_extraction is True + assert response.redact is True + + +@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_entity_type.EntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_entity_type( + entity_type=gcdc_entity_type.EntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].entity_type == gcdc_entity_type.EntityType(name='name_value') + assert args[0].update_mask == field_mask_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( + gcdc_entity_type.UpdateEntityTypeRequest(), + entity_type=gcdc_entity_type.EntityType(name='name_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 = gcdc_entity_type.EntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( + gcdc_entity_type.UpdateEntityTypeRequest(), + entity_type=gcdc_entity_type.EntityType(name='name_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_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.dialogflowcx_v3beta1.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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_entity_types_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + 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.dialogflowcx_v3beta1.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_type_path(): + project = "squid" + location = "clam" + agent = "whelk" + entity_type = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + actual = EntityTypesClient.entity_type_path(project, location, agent, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "entity_type": "mussel", + } + 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 = "winkle" + 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": "nautilus", + } + 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 = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = EntityTypesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + 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 = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EntityTypesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + 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 = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = EntityTypesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + 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 = "oyster" + location = "nudibranch" + 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": "cuttlefish", + "location": "mussel", + } + 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py new file mode 100644 index 00000000..26832174 --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py @@ -0,0 +1,3467 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.environments import EnvironmentsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.environments import EnvironmentsClient +from google.cloud.dialogflowcx_v3beta1.services.environments import pagers +from google.cloud.dialogflowcx_v3beta1.services.environments import transports +from google.cloud.dialogflowcx_v3beta1.services.environments.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.environments.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import environment +from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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(): + 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.dialogflowcx_v3beta1.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', + display_name='display_name_value', + description='description_value', + ) + response = client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +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', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@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_get_environment_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.get_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_environment( + name='name_value', + ) + + # Establish that the 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_environment_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.get_environment( + environment.GetEnvironmentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_environment_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.get_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_environment( + 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_environment_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.get_environment( + environment.GetEnvironmentRequest(), + name='name_value', + ) + + +def test_create_environment(transport: str = 'grpc', request_type=gcdc_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 = operations_pb2.Operation(name='operations/spam') + response = client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +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] == gcdc_environment.CreateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@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 = gcdc_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 = operations_pb2.Operation(name='operations/op') + 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 = gcdc_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(operations_pb2.Operation(name='operations/op')) + 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_create_environment_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.create_environment), + '__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_environment( + parent='parent_value', + environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') + + +def test_create_environment_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.create_environment( + gcdc_environment.CreateEnvironmentRequest(), + parent='parent_value', + environment=gcdc_environment.Environment(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_environment_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.create_environment), + '__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_environment( + parent='parent_value', + environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') + + +@pytest.mark.asyncio +async def test_create_environment_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.create_environment( + gcdc_environment.CreateEnvironmentRequest(), + parent='parent_value', + environment=gcdc_environment.Environment(name='name_value'), + ) + + +def test_update_environment(transport: str = 'grpc', request_type=gcdc_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 = operations_pb2.Operation(name='operations/spam') + response = client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +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] == gcdc_environment.UpdateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@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 = gcdc_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 = operations_pb2.Operation(name='operations/op') + 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 = gcdc_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(operations_pb2.Operation(name='operations/op')) + 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_update_environment_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.update_environment), + '__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_environment( + environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_environment_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.update_environment( + gcdc_environment.UpdateEnvironmentRequest(), + environment=gcdc_environment.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_environment_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.update_environment), + '__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_environment( + environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_environment_flattened_error_async(): + client = EnvironmentsAsyncClient( + credentials=ga_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_environment( + gcdc_environment.UpdateEnvironmentRequest(), + environment=gcdc_environment.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +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_delete_environment_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.delete_environment), + '__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_environment( + 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_environment_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.delete_environment( + environment.DeleteEnvironmentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_environment_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.delete_environment), + '__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_environment( + 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_environment_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.delete_environment( + environment.DeleteEnvironmentRequest(), + name='name_value', + ) + + +def test_lookup_environment_history(transport: str = 'grpc', request_type=environment.LookupEnvironmentHistoryRequest): + 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.lookup_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.LookupEnvironmentHistoryResponse( + next_page_token='next_page_token_value', + ) + response = client.lookup_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.LookupEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.LookupEnvironmentHistoryPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_lookup_environment_history_from_dict(): + test_lookup_environment_history(request_type=dict) + + +def test_lookup_environment_history_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lookup_environment_history), + '__call__') as call: + client.lookup_environment_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.LookupEnvironmentHistoryRequest() + + +@pytest.mark.asyncio +async def test_lookup_environment_history_async(transport: str = 'grpc_asyncio', request_type=environment.LookupEnvironmentHistoryRequest): + 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.lookup_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse( + next_page_token='next_page_token_value', + )) + response = await client.lookup_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.LookupEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.LookupEnvironmentHistoryAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_lookup_environment_history_async_from_dict(): + await test_lookup_environment_history_async(request_type=dict) + + +def test_lookup_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.LookupEnvironmentHistoryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lookup_environment_history), + '__call__') as call: + call.return_value = environment.LookupEnvironmentHistoryResponse() + client.lookup_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_lookup_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.LookupEnvironmentHistoryRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lookup_environment_history), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse()) + await client.lookup_environment_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_lookup_environment_history_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.lookup_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.LookupEnvironmentHistoryResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.lookup_environment_history( + name='name_value', + ) + + # Establish that the 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_lookup_environment_history_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.lookup_environment_history( + environment.LookupEnvironmentHistoryRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_lookup_environment_history_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.lookup_environment_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.LookupEnvironmentHistoryResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.lookup_environment_history( + 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_lookup_environment_history_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.lookup_environment_history( + environment.LookupEnvironmentHistoryRequest(), + name='name_value', + ) + + +def test_lookup_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.lookup_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[], + next_page_token='def', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), + ) + pager = client.lookup_environment_history(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_lookup_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.lookup_environment_history), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[], + next_page_token='def', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + pages = list(client.lookup_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_lookup_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.lookup_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[], + next_page_token='def', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + async_pager = await client.lookup_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.Environment) + for i in responses) + +@pytest.mark.asyncio +async def test_lookup_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.lookup_environment_history), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + environment.Environment(), + ], + next_page_token='abc', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[], + next_page_token='def', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + ], + next_page_token='ghi', + ), + environment.LookupEnvironmentHistoryResponse( + environments=[ + environment.Environment(), + environment.Environment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.lookup_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_run_continuous_test(transport: str = 'grpc', request_type=environment.RunContinuousTestRequest): + 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.run_continuous_test), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_continuous_test(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.RunContinuousTestRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_continuous_test_from_dict(): + test_run_continuous_test(request_type=dict) + + +def test_run_continuous_test_empty_call(): + # 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.run_continuous_test), + '__call__') as call: + client.run_continuous_test() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.RunContinuousTestRequest() + + +@pytest.mark.asyncio +async def test_run_continuous_test_async(transport: str = 'grpc_asyncio', request_type=environment.RunContinuousTestRequest): + 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.run_continuous_test), + '__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.run_continuous_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.RunContinuousTestRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_continuous_test_async_from_dict(): + await test_run_continuous_test_async(request_type=dict) + + +def test_run_continuous_test_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.RunContinuousTestRequest() + + request.environment = 'environment/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_continuous_test), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_continuous_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=environment/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_continuous_test_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.RunContinuousTestRequest() + + request.environment = 'environment/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_continuous_test), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_continuous_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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=environment/value', + ) in kw['metadata'] + + +def test_list_continuous_test_results(transport: str = 'grpc', request_type=environment.ListContinuousTestResultsRequest): + 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_continuous_test_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListContinuousTestResultsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_continuous_test_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListContinuousTestResultsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListContinuousTestResultsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_continuous_test_results_from_dict(): + test_list_continuous_test_results(request_type=dict) + + +def test_list_continuous_test_results_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = 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_continuous_test_results), + '__call__') as call: + client.list_continuous_test_results() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListContinuousTestResultsRequest() + + +@pytest.mark.asyncio +async def test_list_continuous_test_results_async(transport: str = 'grpc_asyncio', request_type=environment.ListContinuousTestResultsRequest): + 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_continuous_test_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.ListContinuousTestResultsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_continuous_test_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListContinuousTestResultsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListContinuousTestResultsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_continuous_test_results_async_from_dict(): + await test_list_continuous_test_results_async(request_type=dict) + + +def test_list_continuous_test_results_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.ListContinuousTestResultsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_continuous_test_results), + '__call__') as call: + call.return_value = environment.ListContinuousTestResultsResponse() + client.list_continuous_test_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_continuous_test_results_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.ListContinuousTestResultsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_continuous_test_results), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListContinuousTestResultsResponse()) + await client.list_continuous_test_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_continuous_test_results_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_continuous_test_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListContinuousTestResultsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_continuous_test_results( + 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_continuous_test_results_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_continuous_test_results( + environment.ListContinuousTestResultsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_continuous_test_results_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_continuous_test_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListContinuousTestResultsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListContinuousTestResultsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_continuous_test_results( + 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_continuous_test_results_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_continuous_test_results( + environment.ListContinuousTestResultsRequest(), + parent='parent_value', + ) + + +def test_list_continuous_test_results_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_continuous_test_results), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + next_page_token='abc', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[], + next_page_token='def', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + ], + next_page_token='ghi', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_continuous_test_results(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.ContinuousTestResult) + for i in results) + +def test_list_continuous_test_results_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_continuous_test_results), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + next_page_token='abc', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[], + next_page_token='def', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + ], + next_page_token='ghi', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_continuous_test_results(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_continuous_test_results_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_continuous_test_results), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + next_page_token='abc', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[], + next_page_token='def', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + ], + next_page_token='ghi', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_continuous_test_results(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.ContinuousTestResult) + for i in responses) + +@pytest.mark.asyncio +async def test_list_continuous_test_results_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_continuous_test_results), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + next_page_token='abc', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[], + next_page_token='def', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + ], + next_page_token='ghi', + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_continuous_test_results(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.dialogflowcx_v3beta1.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', + 'lookup_environment_history', + 'run_continuous_test', + 'list_continuous_test_results', + ) + 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_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.dialogflowcx_v3beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_environments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (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.dialogflowcx_v3beta1.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_environments_grpc_lro_client(): + client = EnvironmentsClient( + 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_environments_grpc_lro_async_client(): + client = EnvironmentsAsyncClient( + 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_continuous_test_result_path(): + project = "squid" + location = "clam" + agent = "whelk" + environment = "octopus" + continuous_test_result = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/continuousTestResults/{continuous_test_result}".format(project=project, location=location, agent=agent, environment=environment, continuous_test_result=continuous_test_result, ) + actual = EnvironmentsClient.continuous_test_result_path(project, location, agent, environment, continuous_test_result) + assert expected == actual + + +def test_parse_continuous_test_result_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "environment": "winkle", + "continuous_test_result": "nautilus", + } + path = EnvironmentsClient.continuous_test_result_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_continuous_test_result_path(path) + assert expected == actual + +def test_environment_path(): + project = "scallop" + location = "abalone" + agent = "squid" + environment = "clam" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + actual = EnvironmentsClient.environment_path(project, location, agent, environment) + assert expected == actual + + +def test_parse_environment_path(): + expected = { + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "environment": "nudibranch", + } + path = EnvironmentsClient.environment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_environment_path(path) + assert expected == actual + +def test_test_case_result_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + test_case = "nautilus" + result = "scallop" + expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) + actual = EnvironmentsClient.test_case_result_path(project, location, agent, test_case, result) + assert expected == actual + + +def test_parse_test_case_result_path(): + expected = { + "project": "abalone", + "location": "squid", + "agent": "clam", + "test_case": "whelk", + "result": "octopus", + } + path = EnvironmentsClient.test_case_result_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_test_case_result_path(path) + assert expected == actual + +def test_version_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + flow = "mussel" + version = "winkle" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + actual = EnvironmentsClient.version_path(project, location, agent, flow, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "agent": "abalone", + "flow": "squid", + "version": "clam", + } + path = EnvironmentsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + 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": "octopus", + } + 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 = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + 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 = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + 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 = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + 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 = "scallop" + location = "abalone" + 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": "squid", + "location": "clam", + } + 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py new file mode 100644 index 00000000..0b79898a --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py @@ -0,0 +1,2911 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.experiments import ExperimentsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.experiments import ExperimentsClient +from google.cloud.dialogflowcx_v3beta1.services.experiments import pagers +from google.cloud.dialogflowcx_v3beta1.services.experiments import transports +from google.cloud.dialogflowcx_v3beta1.services.experiments.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.experiments.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import experiment +from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # 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(): + 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 ExperimentsClient._get_default_mtls_endpoint(None) is None + assert ExperimentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ExperimentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ExperimentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ExperimentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ExperimentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + ExperimentsClient, + ExperimentsAsyncClient, +]) +def test_experiments_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", [ + ExperimentsClient, + ExperimentsAsyncClient, +]) +def test_experiments_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_experiments_client_get_transport_class(): + transport = ExperimentsClient.get_transport_class() + available_transports = [ + transports.ExperimentsGrpcTransport, + ] + assert transport in available_transports + + transport = ExperimentsClient.get_transport_class("grpc") + assert transport == transports.ExperimentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient)) +@mock.patch.object(ExperimentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsAsyncClient)) +def test_experiments_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(ExperimentsClient, '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(ExperimentsClient, '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", [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "true"), + (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "false"), + (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient)) +@mock.patch.object(ExperimentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_experiments_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", [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_experiments_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", [ + (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), + (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_experiments_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_experiments_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ExperimentsClient( + 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_experiments(transport: str = 'grpc', request_type=experiment.ListExperimentsRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.ListExperimentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExperimentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_experiments_from_dict(): + test_list_experiments(request_type=dict) + + +def test_list_experiments_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=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_experiments), + '__call__') as call: + client.list_experiments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.ListExperimentsRequest() + + +@pytest.mark.asyncio +async def test_list_experiments_async(transport: str = 'grpc_asyncio', request_type=experiment.ListExperimentsRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.ListExperimentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExperimentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_experiments_async_from_dict(): + await test_list_experiments_async(request_type=dict) + + +def test_list_experiments_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.ListExperimentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + call.return_value = experiment.ListExperimentsResponse() + client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_experiments_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.ListExperimentsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse()) + await client.list_experiments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_experiments_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_experiments( + parent='parent_value', + ) + + # Establish that the 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_experiments_flattened_error(): + client = ExperimentsClient( + credentials=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_experiments( + experiment.ListExperimentsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_experiments_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.ListExperimentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_experiments( + 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_experiments_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_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_experiments( + experiment.ListExperimentsRequest(), + parent='parent_value', + ) + + +def test_list_experiments_pager(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token='abc', + ), + experiment.ListExperimentsResponse( + experiments=[], + next_page_token='def', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + ], + next_page_token='ghi', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_experiments(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, experiment.Experiment) + for i in results) + +def test_list_experiments_pages(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token='abc', + ), + experiment.ListExperimentsResponse( + experiments=[], + next_page_token='def', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + ], + next_page_token='ghi', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_experiments(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_experiments_async_pager(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token='abc', + ), + experiment.ListExperimentsResponse( + experiments=[], + next_page_token='def', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + ], + next_page_token='ghi', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_experiments(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, experiment.Experiment) + for i in responses) + +@pytest.mark.asyncio +async def test_list_experiments_async_pages(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_experiments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + experiment.Experiment(), + ], + next_page_token='abc', + ), + experiment.ListExperimentsResponse( + experiments=[], + next_page_token='def', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + ], + next_page_token='ghi', + ), + experiment.ListExperimentsResponse( + experiments=[ + experiment.Experiment(), + experiment.Experiment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_experiments(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_experiment(transport: str = 'grpc', request_type=experiment.GetExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + ) + response = client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.GetExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +def test_get_experiment_from_dict(): + test_get_experiment(request_type=dict) + + +def test_get_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=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_experiment), + '__call__') as call: + client.get_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.GetExperimentRequest() + + +@pytest.mark.asyncio +async def test_get_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.GetExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + )) + response = await client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.GetExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_get_experiment_async_from_dict(): + await test_get_experiment_async(request_type=dict) + + +def test_get_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.GetExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_experiment), + '__call__') as call: + call.return_value = experiment.Experiment() + client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.GetExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + await client.get_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_experiment( + name='name_value', + ) + + # Establish that the 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_experiment_flattened_error(): + client = ExperimentsClient( + credentials=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_experiment( + experiment.GetExperimentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_experiment( + 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_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_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_experiment( + experiment.GetExperimentRequest(), + name='name_value', + ) + + +def test_create_experiment(transport: str = 'grpc', request_type=gcdc_experiment.CreateExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_experiment.Experiment.State.DRAFT, + ) + response = client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.CreateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +def test_create_experiment_from_dict(): + test_create_experiment(request_type=dict) + + +def test_create_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=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_experiment), + '__call__') as call: + client.create_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.CreateExperimentRequest() + + +@pytest.mark.asyncio +async def test_create_experiment_async(transport: str = 'grpc_asyncio', request_type=gcdc_experiment.CreateExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_experiment.Experiment.State.DRAFT, + )) + response = await client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.CreateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_create_experiment_async_from_dict(): + await test_create_experiment_async(request_type=dict) + + +def test_create_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_experiment.CreateExperimentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), + '__call__') as call: + call.return_value = gcdc_experiment.Experiment() + client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_experiment.CreateExperimentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) + await client.create_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_experiment( + parent='parent_value', + experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') + + +def test_create_experiment_flattened_error(): + client = ExperimentsClient( + credentials=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_experiment( + gcdc_experiment.CreateExperimentRequest(), + parent='parent_value', + experiment=gcdc_experiment.Experiment(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_experiment( + parent='parent_value', + experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') + + +@pytest.mark.asyncio +async def test_create_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_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_experiment( + gcdc_experiment.CreateExperimentRequest(), + parent='parent_value', + experiment=gcdc_experiment.Experiment(name='name_value'), + ) + + +def test_update_experiment(transport: str = 'grpc', request_type=gcdc_experiment.UpdateExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_experiment.Experiment.State.DRAFT, + ) + response = client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.UpdateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +def test_update_experiment_from_dict(): + test_update_experiment(request_type=dict) + + +def test_update_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=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_experiment), + '__call__') as call: + client.update_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.UpdateExperimentRequest() + + +@pytest.mark.asyncio +async def test_update_experiment_async(transport: str = 'grpc_asyncio', request_type=gcdc_experiment.UpdateExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_experiment.Experiment.State.DRAFT, + )) + response = await client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_experiment.UpdateExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_update_experiment_async_from_dict(): + await test_update_experiment_async(request_type=dict) + + +def test_update_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_experiment.UpdateExperimentRequest() + + request.experiment.name = 'experiment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), + '__call__') as call: + call.return_value = gcdc_experiment.Experiment() + client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'experiment.name=experiment.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_experiment.UpdateExperimentRequest() + + request.experiment.name = 'experiment.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) + await client.update_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'experiment.name=experiment.name/value', + ) in kw['metadata'] + + +def test_update_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_experiment( + experiment=gcdc_experiment.Experiment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].experiment == gcdc_experiment.Experiment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_experiment_flattened_error(): + client = ExperimentsClient( + credentials=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_experiment( + gcdc_experiment.UpdateExperimentRequest(), + experiment=gcdc_experiment.Experiment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_experiment( + experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_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_experiment( + gcdc_experiment.UpdateExperimentRequest(), + experiment=gcdc_experiment.Experiment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_experiment(transport: str = 'grpc', request_type=experiment.DeleteExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.DeleteExperimentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_experiment_from_dict(): + test_delete_experiment(request_type=dict) + + +def test_delete_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=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_experiment), + '__call__') as call: + client.delete_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.DeleteExperimentRequest() + + +@pytest.mark.asyncio +async def test_delete_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.DeleteExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.DeleteExperimentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_experiment_async_from_dict(): + await test_delete_experiment_async(request_type=dict) + + +def test_delete_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.DeleteExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), + '__call__') as call: + call.return_value = None + client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.DeleteExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), + '__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_experiment( + 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_experiment_flattened_error(): + client = ExperimentsClient( + credentials=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_experiment( + experiment.DeleteExperimentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_experiment), + '__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_experiment( + 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_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_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_experiment( + experiment.DeleteExperimentRequest(), + name='name_value', + ) + + +def test_start_experiment(transport: str = 'grpc', request_type=experiment.StartExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + ) + response = client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StartExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +def test_start_experiment_from_dict(): + test_start_experiment(request_type=dict) + + +def test_start_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + client.start_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StartExperimentRequest() + + +@pytest.mark.asyncio +async def test_start_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.StartExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + )) + response = await client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StartExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_start_experiment_async_from_dict(): + await test_start_experiment_async(request_type=dict) + + +def test_start_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.StartExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + call.return_value = experiment.Experiment() + client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.StartExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + await client.start_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_start_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_experiment( + name='name_value', + ) + + # Establish that the 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_start_experiment_flattened_error(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.start_experiment( + experiment.StartExperimentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_start_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.start_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_experiment( + 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_start_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.start_experiment( + experiment.StartExperimentRequest(), + name='name_value', + ) + + +def test_stop_experiment(transport: str = 'grpc', request_type=experiment.StopExperimentRequest): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + ) + response = client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StopExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +def test_stop_experiment_from_dict(): + test_stop_experiment(request_type=dict) + + +def test_stop_experiment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + client.stop_experiment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StopExperimentRequest() + + +@pytest.mark.asyncio +async def test_stop_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.StopExperimentRequest): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( + name='name_value', + display_name='display_name_value', + description='description_value', + state=experiment.Experiment.State.DRAFT, + )) + response = await client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == experiment.StopExperimentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, experiment.Experiment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == experiment.Experiment.State.DRAFT + + +@pytest.mark.asyncio +async def test_stop_experiment_async_from_dict(): + await test_stop_experiment_async(request_type=dict) + + +def test_stop_experiment_field_headers(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.StopExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + call.return_value = experiment.Experiment() + client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_experiment_field_headers_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = experiment.StopExperimentRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + await client.stop_experiment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_stop_experiment_flattened(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.stop_experiment( + name='name_value', + ) + + # Establish that the 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_stop_experiment_flattened_error(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.stop_experiment( + experiment.StopExperimentRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_stop_experiment_flattened_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_experiment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = experiment.Experiment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.stop_experiment( + 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_stop_experiment_flattened_error_async(): + client = ExperimentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.stop_experiment( + experiment.StopExperimentRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ExperimentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ExperimentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ExperimentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ExperimentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ExperimentsGrpcTransport, + transports.ExperimentsGrpcAsyncIOTransport, +]) +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 = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ExperimentsGrpcTransport, + ) + +def test_experiments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ExperimentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_experiments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ExperimentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_experiments', + 'get_experiment', + 'create_experiment', + 'update_experiment', + 'delete_experiment', + 'start_experiment', + 'stop_experiment', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_experiments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExperimentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_experiments_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExperimentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_experiments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ExperimentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_experiments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ExperimentsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_experiments_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ExperimentsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ExperimentsGrpcTransport, + transports.ExperimentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_experiments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ExperimentsGrpcTransport, + transports.ExperimentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_experiments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_experiments_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_experiments_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_experiments_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) +def test_experiments_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = 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_experiments_host_no_port(): + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_experiments_host_with_port(): + client = ExperimentsClient( + 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_experiments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ExperimentsGrpcTransport( + 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_experiments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ExperimentsGrpcAsyncIOTransport( + 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.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) +def test_experiments_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.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) +def test_experiments_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_experiment_path(): + project = "squid" + location = "clam" + agent = "whelk" + environment = "octopus" + experiment = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format(project=project, location=location, agent=agent, environment=environment, experiment=experiment, ) + actual = ExperimentsClient.experiment_path(project, location, agent, environment, experiment) + assert expected == actual + + +def test_parse_experiment_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "environment": "winkle", + "experiment": "nautilus", + } + path = ExperimentsClient.experiment_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_experiment_path(path) + assert expected == actual + +def test_version_path(): + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" + version = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + actual = ExperimentsClient.version_path(project, location, agent, flow, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "version": "mussel", + } + path = ExperimentsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_version_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ExperimentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ExperimentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = ExperimentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ExperimentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ExperimentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ExperimentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = ExperimentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ExperimentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.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 = ExperimentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ExperimentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ExperimentsClient.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.ExperimentsTransport, '_prep_wrapped_messages') as prep: + client = ExperimentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ExperimentsTransport, '_prep_wrapped_messages') as prep: + transport_class = ExperimentsClient.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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py new file mode 100644 index 00000000..bfc8cd15 --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py @@ -0,0 +1,3472 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.flows import FlowsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.flows import FlowsClient +from google.cloud.dialogflowcx_v3beta1.services.flows import pagers +from google.cloud.dialogflowcx_v3beta1.services.flows import transports +from google.cloud.dialogflowcx_v3beta1.services.flows.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.flows.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import flow +from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow +from google.cloud.dialogflowcx_v3beta1.types import fulfillment +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import response_message +from google.cloud.dialogflowcx_v3beta1.types import validation_message +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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(): + 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 FlowsClient._get_default_mtls_endpoint(None) is None + assert FlowsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert FlowsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert FlowsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert FlowsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert FlowsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + FlowsClient, + FlowsAsyncClient, +]) +def test_flows_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", [ + FlowsClient, + FlowsAsyncClient, +]) +def test_flows_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_flows_client_get_transport_class(): + transport = FlowsClient.get_transport_class() + available_transports = [ + transports.FlowsGrpcTransport, + ] + assert transport in available_transports + + transport = FlowsClient.get_transport_class("grpc") + assert transport == transports.FlowsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (FlowsClient, transports.FlowsGrpcTransport, "grpc"), + (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(FlowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsClient)) +@mock.patch.object(FlowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsAsyncClient)) +def test_flows_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(FlowsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=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(FlowsClient, '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", [ + (FlowsClient, transports.FlowsGrpcTransport, "grpc", "true"), + (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (FlowsClient, transports.FlowsGrpcTransport, "grpc", "false"), + (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(FlowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsClient)) +@mock.patch.object(FlowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_flows_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", [ + (FlowsClient, transports.FlowsGrpcTransport, "grpc"), + (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_flows_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", [ + (FlowsClient, transports.FlowsGrpcTransport, "grpc"), + (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_flows_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_flows_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = FlowsClient( + 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_flow(transport: str = 'grpc', request_type=gcdc_flow.CreateFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.create_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.CreateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_create_flow_from_dict(): + test_create_flow(request_type=dict) + + +def test_create_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow), + '__call__') as call: + client.create_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.CreateFlowRequest() + + +@pytest.mark.asyncio +async def test_create_flow_async(transport: str = 'grpc_asyncio', request_type=gcdc_flow.CreateFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.create_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.CreateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_create_flow_async_from_dict(): + await test_create_flow_async(request_type=dict) + + +def test_create_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_flow.CreateFlowRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + call.return_value = gcdc_flow.Flow() + client.create_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_flow.CreateFlowRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) + await client.create_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_flow_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_flow( + parent='parent_value', + flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') + + +def test_create_flow_flattened_error(): + client = FlowsClient( + credentials=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_flow( + gcdc_flow.CreateFlowRequest(), + parent='parent_value', + flow=gcdc_flow.Flow(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_flow_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_flow( + parent='parent_value', + flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') + + +@pytest.mark.asyncio +async def test_create_flow_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow( + gcdc_flow.CreateFlowRequest(), + parent='parent_value', + flow=gcdc_flow.Flow(name='name_value'), + ) + + +def test_delete_flow(transport: str = 'grpc', request_type=flow.DeleteFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.DeleteFlowRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_flow_from_dict(): + test_delete_flow(request_type=dict) + + +def test_delete_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow), + '__call__') as call: + client.delete_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.DeleteFlowRequest() + + +@pytest.mark.asyncio +async def test_delete_flow_async(transport: str = 'grpc_asyncio', request_type=flow.DeleteFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.DeleteFlowRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_flow_async_from_dict(): + await test_delete_flow_async(request_type=dict) + + +def test_delete_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.DeleteFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + call.return_value = None + client.delete_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.DeleteFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_flow( + name='name_value', + ) + + # Establish that the 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_flow_flattened_error(): + client = FlowsClient( + credentials=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_flow( + flow.DeleteFlowRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_flow_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_flow), + '__call__') as call: + # 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_flow( + 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_flow_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow( + flow.DeleteFlowRequest(), + name='name_value', + ) + + +def test_list_flows(transport: str = 'grpc', request_type=flow.ListFlowsRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.ListFlowsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_flows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ListFlowsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFlowsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_flows_from_dict(): + test_list_flows(request_type=dict) + + +def test_list_flows_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flows), + '__call__') as call: + client.list_flows() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ListFlowsRequest() + + +@pytest.mark.asyncio +async def test_list_flows_async(transport: str = 'grpc_asyncio', request_type=flow.ListFlowsRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_flows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ListFlowsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFlowsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_flows_async_from_dict(): + await test_list_flows_async(request_type=dict) + + +def test_list_flows_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ListFlowsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + call.return_value = flow.ListFlowsResponse() + client.list_flows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_flows_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ListFlowsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse()) + await client.list_flows(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_flows_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.ListFlowsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_flows( + parent='parent_value', + ) + + # Establish that the 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_flows_flattened_error(): + client = FlowsClient( + credentials=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_flows( + flow.ListFlowsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_flows_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.ListFlowsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_flows( + 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_flows_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flows( + flow.ListFlowsRequest(), + parent='parent_value', + ) + + +def test_list_flows_pager(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + flow.Flow(), + ], + next_page_token='abc', + ), + flow.ListFlowsResponse( + flows=[], + next_page_token='def', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + ], + next_page_token='ghi', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_flows(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, flow.Flow) + for i in results) + +def test_list_flows_pages(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + flow.Flow(), + ], + next_page_token='abc', + ), + flow.ListFlowsResponse( + flows=[], + next_page_token='def', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + ], + next_page_token='ghi', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + ], + ), + RuntimeError, + ) + pages = list(client.list_flows(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_flows_async_pager(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + flow.Flow(), + ], + next_page_token='abc', + ), + flow.ListFlowsResponse( + flows=[], + next_page_token='def', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + ], + next_page_token='ghi', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_flows(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, flow.Flow) + for i in responses) + +@pytest.mark.asyncio +async def test_list_flows_async_pages(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_flows), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + flow.Flow(), + ], + next_page_token='abc', + ), + flow.ListFlowsResponse( + flows=[], + next_page_token='def', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + ], + next_page_token='ghi', + ), + flow.ListFlowsResponse( + flows=[ + flow.Flow(), + flow.Flow(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_flows(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_flow(transport: str = 'grpc', request_type=flow.GetFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.get_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_get_flow_from_dict(): + test_get_flow(request_type=dict) + + +def test_get_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow), + '__call__') as call: + client.get_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowRequest() + + +@pytest.mark.asyncio +async def test_get_flow_async(transport: str = 'grpc_asyncio', request_type=flow.GetFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.get_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_get_flow_async_from_dict(): + await test_get_flow_async(request_type=dict) + + +def test_get_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.GetFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + call.return_value = flow.Flow() + client.get_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.GetFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow()) + await client.get_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.Flow() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_flow( + name='name_value', + ) + + # Establish that the 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_flow_flattened_error(): + client = FlowsClient( + credentials=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_flow( + flow.GetFlowRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_flow_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.Flow() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_flow( + 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_flow_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow( + flow.GetFlowRequest(), + name='name_value', + ) + + +def test_update_flow(transport: str = 'grpc', request_type=gcdc_flow.UpdateFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.update_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.UpdateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_update_flow_from_dict(): + test_update_flow(request_type=dict) + + +def test_update_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow), + '__call__') as call: + client.update_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.UpdateFlowRequest() + + +@pytest.mark.asyncio +async def test_update_flow_async(transport: str = 'grpc_asyncio', request_type=gcdc_flow.UpdateFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow( + name='name_value', + display_name='display_name_value', + description='description_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.update_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_flow.UpdateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_flow.Flow) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_update_flow_async_from_dict(): + await test_update_flow_async(request_type=dict) + + +def test_update_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_flow.UpdateFlowRequest() + + request.flow.name = 'flow.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + call.return_value = gcdc_flow.Flow() + client.update_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'flow.name=flow.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_flow.UpdateFlowRequest() + + request.flow.name = 'flow.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) + await client.update_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'flow.name=flow.name/value', + ) in kw['metadata'] + + +def test_update_flow_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_flow( + flow=gcdc_flow.Flow(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].flow == gcdc_flow.Flow(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_flow_flattened_error(): + client = FlowsClient( + credentials=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_flow( + gcdc_flow.UpdateFlowRequest(), + flow=gcdc_flow.Flow(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_flow_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_flow.Flow() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_flow( + flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_flow_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow( + gcdc_flow.UpdateFlowRequest(), + flow=gcdc_flow.Flow(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_train_flow(transport: str = 'grpc', request_type=flow.TrainFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.train_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.TrainFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_train_flow_from_dict(): + test_train_flow(request_type=dict) + + +def test_train_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow), + '__call__') as call: + client.train_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.TrainFlowRequest() + + +@pytest.mark.asyncio +async def test_train_flow_async(transport: str = 'grpc_asyncio', request_type=flow.TrainFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.train_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.TrainFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_train_flow_async_from_dict(): + await test_train_flow_async(request_type=dict) + + +def test_train_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.TrainFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.train_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_train_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.TrainFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.train_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_train_flow_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.train_flow( + name='name_value', + ) + + # Establish that the 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_train_flow_flattened_error(): + client = FlowsClient( + credentials=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_flow( + flow.TrainFlowRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_train_flow_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_flow), + '__call__') as call: + # 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_flow( + 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_train_flow_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow( + flow.TrainFlowRequest(), + name='name_value', + ) + + +def test_validate_flow(transport: str = 'grpc', request_type=flow.ValidateFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.FlowValidationResult( + name='name_value', + ) + response = client.validate_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ValidateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.FlowValidationResult) + assert response.name == 'name_value' + + +def test_validate_flow_from_dict(): + test_validate_flow(request_type=dict) + + +def test_validate_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_flow), + '__call__') as call: + client.validate_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ValidateFlowRequest() + + +@pytest.mark.asyncio +async def test_validate_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ValidateFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult( + name='name_value', + )) + response = await client.validate_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ValidateFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.FlowValidationResult) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_validate_flow_async_from_dict(): + await test_validate_flow_async(request_type=dict) + + +def test_validate_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ValidateFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_flow), + '__call__') as call: + call.return_value = flow.FlowValidationResult() + client.validate_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_validate_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ValidateFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.validate_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) + await client.validate_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_validation_result(transport: str = 'grpc', request_type=flow.GetFlowValidationResultRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.FlowValidationResult( + name='name_value', + ) + response = client.get_flow_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.FlowValidationResult) + assert response.name == 'name_value' + + +def test_get_flow_validation_result_from_dict(): + test_get_flow_validation_result(request_type=dict) + + +def test_get_flow_validation_result_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=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_flow_validation_result), + '__call__') as call: + client.get_flow_validation_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowValidationResultRequest() + + +@pytest.mark.asyncio +async def test_get_flow_validation_result_async(transport: str = 'grpc_asyncio', request_type=flow.GetFlowValidationResultRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult( + name='name_value', + )) + response = await client.get_flow_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.GetFlowValidationResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, flow.FlowValidationResult) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_flow_validation_result_async_from_dict(): + await test_get_flow_validation_result_async(request_type=dict) + + +def test_get_flow_validation_result_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.GetFlowValidationResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + call.return_value = flow.FlowValidationResult() + client.get_flow_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_validation_result_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.GetFlowValidationResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) + await client.get_flow_validation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_flow_validation_result_flattened(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.FlowValidationResult() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_flow_validation_result( + name='name_value', + ) + + # Establish that the 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_flow_validation_result_flattened_error(): + client = FlowsClient( + credentials=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_flow_validation_result( + flow.GetFlowValidationResultRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_flow_validation_result_flattened_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_flow_validation_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = flow.FlowValidationResult() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_flow_validation_result( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_flow_validation_result_flattened_error_async(): + client = FlowsAsyncClient( + credentials=ga_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_flow_validation_result( + flow.GetFlowValidationResultRequest(), + name='name_value', + ) + + +def test_import_flow(transport: str = 'grpc', request_type=flow.ImportFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_flow_from_dict(): + test_import_flow(request_type=dict) + + +def test_import_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_flow), + '__call__') as call: + client.import_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + +@pytest.mark.asyncio +async def test_import_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ImportFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_flow_async_from_dict(): + await test_import_flow_async(request_type=dict) + + +def test_import_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ImportFlowRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_flow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ImportFlowRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_export_flow(transport: str = 'grpc', request_type=flow.ExportFlowRequest): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_flow_from_dict(): + test_export_flow(request_type=dict) + + +def test_export_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_flow), + '__call__') as call: + client.export_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + +@pytest.mark.asyncio +async def test_export_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ExportFlowRequest): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_flow), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_flow_async_from_dict(): + await test_export_flow_async(request_type=dict) + + +def test_export_flow_field_headers(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ExportFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_flow), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_export_flow_field_headers_async(): + client = FlowsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = flow.ExportFlowRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_flow), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FlowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FlowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FlowsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FlowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FlowsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FlowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FlowsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FlowsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FlowsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.FlowsGrpcTransport, + transports.FlowsGrpcAsyncIOTransport, +]) +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 = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FlowsGrpcTransport, + ) + +def test_flows_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FlowsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_flows_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.FlowsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_flow', + 'delete_flow', + 'list_flows', + 'get_flow', + 'update_flow', + 'train_flow', + 'validate_flow', + 'get_flow_validation_result', + 'import_flow', + 'export_flow', + ) + 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_flows_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FlowsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_flows_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FlowsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_flows_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FlowsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_flows_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FlowsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_flows_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FlowsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FlowsGrpcTransport, + transports.FlowsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_flows_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FlowsGrpcTransport, + transports.FlowsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_flows_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_flows_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_flows_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_flows_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) +def test_flows_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = 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_flows_host_no_port(): + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_flows_host_with_port(): + client = FlowsClient( + 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_flows_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FlowsGrpcTransport( + 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_flows_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FlowsGrpcAsyncIOTransport( + 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.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) +def test_flows_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.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) +def test_flows_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_flows_grpc_lro_client(): + client = FlowsClient( + 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_flows_grpc_lro_async_client(): + client = FlowsAsyncClient( + 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_flow_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = FlowsClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "flow": "mussel", + } + path = FlowsClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_flow_path(path) + assert expected == actual + +def test_flow_validation_result_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + flow = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) + actual = FlowsClient.flow_validation_result_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_validation_result_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "flow": "octopus", + } + path = FlowsClient.flow_validation_result_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_flow_validation_result_path(path) + assert expected == actual + +def test_intent_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + intent = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = FlowsClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "intent": "abalone", + } + path = FlowsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_intent_path(path) + assert expected == actual + +def test_page_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + page = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + actual = FlowsClient.page_path(project, location, agent, flow, page) + assert expected == actual + + +def test_parse_page_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "flow": "winkle", + "page": "nautilus", + } + path = FlowsClient.page_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_page_path(path) + assert expected == actual + +def test_transition_route_group_path(): + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" + transition_route_group = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + actual = FlowsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) + assert expected == actual + + +def test_parse_transition_route_group_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "transition_route_group": "mussel", + } + path = FlowsClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_transition_route_group_path(path) + assert expected == actual + +def test_webhook_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = FlowsClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", + } + path = FlowsClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = FlowsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = FlowsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = FlowsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = FlowsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = FlowsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = FlowsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = FlowsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = FlowsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.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 = FlowsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = FlowsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.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.FlowsTransport, '_prep_wrapped_messages') as prep: + client = FlowsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.FlowsTransport, '_prep_wrapped_messages') as prep: + transport_class = FlowsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py new file mode 100644 index 00000000..7f89a9e5 --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py @@ -0,0 +1,2429 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.intents import IntentsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.intents import IntentsClient +from google.cloud.dialogflowcx_v3beta1.services.intents import pagers +from google.cloud.dialogflowcx_v3beta1.services.intents import transports +from google.cloud.dialogflowcx_v3beta1.services.intents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.intents.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import intent +from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3beta1.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', + ) + + # Establish that the 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_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', + ) + + +@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', + ) + + # Establish that 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_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', + ) + + +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', + priority=898, + is_fallback=True, + description='description_value', + ) + response = client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == intent.GetIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +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', + priority=898, + is_fallback=True, + description='description_value', + )) + response = await client.get_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == intent.GetIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +@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', + ) + + # Establish that the 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_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', + ) + + +@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', + ) + + # Establish that 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_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', + ) + + +def test_create_intent(transport: str = 'grpc', request_type=gcdc_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 = gcdc_intent.Intent( + name='name_value', + display_name='display_name_value', + priority=898, + is_fallback=True, + description='description_value', + ) + response = client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_intent.CreateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +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] == gcdc_intent.CreateIntentRequest() + + +@pytest.mark.asyncio +async def test_create_intent_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_intent.Intent( + name='name_value', + display_name='display_name_value', + priority=898, + is_fallback=True, + description='description_value', + )) + response = await client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_intent.CreateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +@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 = gcdc_intent.CreateIntentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + call.return_value = gcdc_intent.Intent() + client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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 = gcdc_intent.CreateIntentRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) + await client.create_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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 = gcdc_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=gcdc_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 == gcdc_intent.Intent(name='name_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( + gcdc_intent.CreateIntentRequest(), + parent='parent_value', + intent=gcdc_intent.Intent(name='name_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 = gcdc_intent.Intent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_intent.Intent(name='name_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( + gcdc_intent.CreateIntentRequest(), + parent='parent_value', + intent=gcdc_intent.Intent(name='name_value'), + ) + + +def test_update_intent(transport: str = 'grpc', request_type=gcdc_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 = gcdc_intent.Intent( + name='name_value', + display_name='display_name_value', + priority=898, + is_fallback=True, + description='description_value', + ) + response = client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_intent.UpdateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +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] == gcdc_intent.UpdateIntentRequest() + + +@pytest.mark.asyncio +async def test_update_intent_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_intent.Intent( + name='name_value', + display_name='display_name_value', + priority=898, + is_fallback=True, + description='description_value', + )) + response = await client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_intent.UpdateIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_intent.Intent) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.priority == 898 + assert response.is_fallback is True + assert response.description == 'description_value' + + +@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 = gcdc_intent.UpdateIntentRequest() + + request.intent.name = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = gcdc_intent.Intent() + client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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 = gcdc_intent.UpdateIntentRequest() + + request.intent.name = 'intent.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) + await client.update_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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 = gcdc_intent.Intent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_intent( + intent=gcdc_intent.Intent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].intent == gcdc_intent.Intent(name='name_value') + assert args[0].update_mask == field_mask_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( + gcdc_intent.UpdateIntentRequest(), + intent=gcdc_intent.Intent(name='name_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 = gcdc_intent.Intent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_intent.Intent(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].intent == gcdc_intent.Intent(name='name_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( + gcdc_intent.UpdateIntentRequest(), + intent=gcdc_intent.Intent(name='name_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_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.dialogflowcx_v3beta1.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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_intents_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_intents_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + 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.dialogflowcx_v3beta1.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_entity_type_path(): + project = "squid" + location = "clam" + agent = "whelk" + entity_type = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + actual = IntentsClient.entity_type_path(project, location, agent, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "entity_type": "mussel", + } + path = IntentsClient.entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = IntentsClient.parse_entity_type_path(path) + assert expected == actual + +def test_intent_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + intent = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = IntentsClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "intent": "octopus", + } + 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 = "oyster" + 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": "nudibranch", + } + 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 = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = IntentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + 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 = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = IntentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + 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 = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = IntentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + 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 = "squid" + location = "clam" + 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": "whelk", + "location": "octopus", + } + 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py new file mode 100644 index 00000000..4d8ad741 --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py @@ -0,0 +1,2504 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.pages import PagesAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.pages import PagesClient +from google.cloud.dialogflowcx_v3beta1.services.pages import pagers +from google.cloud.dialogflowcx_v3beta1.services.pages import transports +from google.cloud.dialogflowcx_v3beta1.services.pages.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.pages.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import fulfillment +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page +from google.cloud.dialogflowcx_v3beta1.types import response_message +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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 PagesClient._get_default_mtls_endpoint(None) is None + assert PagesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PagesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PagesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PagesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PagesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + PagesClient, + PagesAsyncClient, +]) +def test_pages_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", [ + PagesClient, + PagesAsyncClient, +]) +def test_pages_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_pages_client_get_transport_class(): + transport = PagesClient.get_transport_class() + available_transports = [ + transports.PagesGrpcTransport, + ] + assert transport in available_transports + + transport = PagesClient.get_transport_class("grpc") + assert transport == transports.PagesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PagesClient, transports.PagesGrpcTransport, "grpc"), + (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(PagesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesClient)) +@mock.patch.object(PagesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesAsyncClient)) +def test_pages_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(PagesClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=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(PagesClient, '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", [ + (PagesClient, transports.PagesGrpcTransport, "grpc", "true"), + (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PagesClient, transports.PagesGrpcTransport, "grpc", "false"), + (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(PagesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesClient)) +@mock.patch.object(PagesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_pages_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", [ + (PagesClient, transports.PagesGrpcTransport, "grpc"), + (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_pages_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", [ + (PagesClient, transports.PagesGrpcTransport, "grpc"), + (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_pages_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_pages_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PagesClient( + 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_pages(transport: str = 'grpc', request_type=page.ListPagesRequest): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_pages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.ListPagesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_pages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == page.ListPagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPagesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_pages_from_dict(): + test_list_pages(request_type=dict) + + +def test_list_pages_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PagesClient( + credentials=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_pages), + '__call__') as call: + client.list_pages() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == page.ListPagesRequest() + + +@pytest.mark.asyncio +async def test_list_pages_async(transport: str = 'grpc_asyncio', request_type=page.ListPagesRequest): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_pages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_pages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == page.ListPagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPagesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_pages_async_from_dict(): + await test_list_pages_async(request_type=dict) + + +def test_list_pages_field_headers(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.ListPagesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + call.return_value = page.ListPagesResponse() + client.list_pages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_pages_field_headers_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.ListPagesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse()) + await client.list_pages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_pages_flattened(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.ListPagesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_pages( + parent='parent_value', + ) + + # Establish that the 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_pages_flattened_error(): + client = PagesClient( + credentials=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_pages( + page.ListPagesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_pages_flattened_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.ListPagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_pages( + 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_pages_flattened_error_async(): + client = PagesAsyncClient( + credentials=ga_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_pages( + page.ListPagesRequest(), + parent='parent_value', + ) + + +def test_list_pages_pager(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + page.Page(), + ], + next_page_token='abc', + ), + page.ListPagesResponse( + pages=[], + next_page_token='def', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + ], + next_page_token='ghi', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_pages(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, page.Page) + for i in results) + +def test_list_pages_pages(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + page.Page(), + ], + next_page_token='abc', + ), + page.ListPagesResponse( + pages=[], + next_page_token='def', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + ], + next_page_token='ghi', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + ], + ), + RuntimeError, + ) + pages = list(client.list_pages(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_pages_async_pager(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + page.Page(), + ], + next_page_token='abc', + ), + page.ListPagesResponse( + pages=[], + next_page_token='def', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + ], + next_page_token='ghi', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_pages(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, page.Page) + for i in responses) + +@pytest.mark.asyncio +async def test_list_pages_async_pages(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_pages), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + page.Page(), + ], + next_page_token='abc', + ), + page.ListPagesResponse( + pages=[], + next_page_token='def', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + ], + next_page_token='ghi', + ), + page.ListPagesResponse( + pages=[ + page.Page(), + page.Page(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_pages(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_page(transport: str = 'grpc', request_type=page.GetPageRequest): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.get_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == page.GetPageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_get_page_from_dict(): + test_get_page(request_type=dict) + + +def test_get_page_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PagesClient( + credentials=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_page), + '__call__') as call: + client.get_page() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == page.GetPageRequest() + + +@pytest.mark.asyncio +async def test_get_page_async(transport: str = 'grpc_asyncio', request_type=page.GetPageRequest): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.get_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == page.GetPageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_get_page_async_from_dict(): + await test_get_page_async(request_type=dict) + + +def test_get_page_field_headers(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.GetPageRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_page), + '__call__') as call: + call.return_value = page.Page() + client.get_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_page_field_headers_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.GetPageRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_page), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.Page()) + await client.get_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_page_flattened(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.Page() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_page( + name='name_value', + ) + + # Establish that the 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_page_flattened_error(): + client = PagesClient( + credentials=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_page( + page.GetPageRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_page_flattened_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = page.Page() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.Page()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_page( + 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_page_flattened_error_async(): + client = PagesAsyncClient( + credentials=ga_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_page( + page.GetPageRequest(), + name='name_value', + ) + + +def test_create_page(transport: str = 'grpc', request_type=gcdc_page.CreatePageRequest): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.create_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.CreatePageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_create_page_from_dict(): + test_create_page(request_type=dict) + + +def test_create_page_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PagesClient( + credentials=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_page), + '__call__') as call: + client.create_page() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.CreatePageRequest() + + +@pytest.mark.asyncio +async def test_create_page_async(transport: str = 'grpc_asyncio', request_type=gcdc_page.CreatePageRequest): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.create_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.CreatePageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_create_page_async_from_dict(): + await test_create_page_async(request_type=dict) + + +def test_create_page_field_headers(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_page.CreatePageRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_page), + '__call__') as call: + call.return_value = gcdc_page.Page() + client.create_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_page_field_headers_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_page.CreatePageRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_page), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) + await client.create_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_page_flattened(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_page( + parent='parent_value', + page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') + + +def test_create_page_flattened_error(): + client = PagesClient( + credentials=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_page( + gcdc_page.CreatePageRequest(), + parent='parent_value', + page=gcdc_page.Page(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_page_flattened_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_page( + parent='parent_value', + page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') + + +@pytest.mark.asyncio +async def test_create_page_flattened_error_async(): + client = PagesAsyncClient( + credentials=ga_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_page( + gcdc_page.CreatePageRequest(), + parent='parent_value', + page=gcdc_page.Page(name='name_value'), + ) + + +def test_update_page(transport: str = 'grpc', request_type=gcdc_page.UpdatePageRequest): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + ) + response = client.update_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.UpdatePageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +def test_update_page_from_dict(): + test_update_page(request_type=dict) + + +def test_update_page_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PagesClient( + credentials=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_page), + '__call__') as call: + client.update_page() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.UpdatePageRequest() + + +@pytest.mark.asyncio +async def test_update_page_async(transport: str = 'grpc_asyncio', request_type=gcdc_page.UpdatePageRequest): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page( + name='name_value', + display_name='display_name_value', + transition_route_groups=['transition_route_groups_value'], + )) + response = await client.update_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_page.UpdatePageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_page.Page) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.transition_route_groups == ['transition_route_groups_value'] + + +@pytest.mark.asyncio +async def test_update_page_async_from_dict(): + await test_update_page_async(request_type=dict) + + +def test_update_page_field_headers(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_page.UpdatePageRequest() + + request.page.name = 'page.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_page), + '__call__') as call: + call.return_value = gcdc_page.Page() + client.update_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'page.name=page.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_page_field_headers_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_page.UpdatePageRequest() + + request.page.name = 'page.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_page), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) + await client.update_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'page.name=page.name/value', + ) in kw['metadata'] + + +def test_update_page_flattened(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_page( + page=gcdc_page.Page(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].page == gcdc_page.Page(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_page_flattened_error(): + client = PagesClient( + credentials=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_page( + gcdc_page.UpdatePageRequest(), + page=gcdc_page.Page(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_page_flattened_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_page.Page() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_page( + page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_page_flattened_error_async(): + client = PagesAsyncClient( + credentials=ga_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_page( + gcdc_page.UpdatePageRequest(), + page=gcdc_page.Page(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_page(transport: str = 'grpc', request_type=page.DeletePageRequest): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == page.DeletePageRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_page_from_dict(): + test_delete_page(request_type=dict) + + +def test_delete_page_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PagesClient( + credentials=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_page), + '__call__') as call: + client.delete_page() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == page.DeletePageRequest() + + +@pytest.mark.asyncio +async def test_delete_page_async(transport: str = 'grpc_asyncio', request_type=page.DeletePageRequest): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == page.DeletePageRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_page_async_from_dict(): + await test_delete_page_async(request_type=dict) + + +def test_delete_page_field_headers(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.DeletePageRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_page), + '__call__') as call: + call.return_value = None + client.delete_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_page_field_headers_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = page.DeletePageRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_page), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_page(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_page_flattened(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_page), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_page( + name='name_value', + ) + + # Establish that the 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_page_flattened_error(): + client = PagesClient( + credentials=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_page( + page.DeletePageRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_page_flattened_async(): + client = PagesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_page), + '__call__') as call: + # 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_page( + 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_page_flattened_error_async(): + client = PagesAsyncClient( + credentials=ga_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_page( + page.DeletePageRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PagesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PagesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PagesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PagesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PagesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PagesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PagesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PagesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PagesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PagesGrpcTransport, + transports.PagesGrpcAsyncIOTransport, +]) +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 = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PagesGrpcTransport, + ) + +def test_pages_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PagesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_pages_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PagesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_pages', + 'get_page', + 'create_page', + 'update_page', + 'delete_page', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_pages_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PagesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_pages_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PagesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_pages_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PagesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_pages_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + PagesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_pages_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + PagesClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PagesGrpcTransport, + transports.PagesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_pages_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PagesGrpcTransport, + transports.PagesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_pages_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_pages_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_pages_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_pages_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) +def test_pages_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = 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_pages_host_no_port(): + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_pages_host_with_port(): + client = PagesClient( + 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_pages_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PagesGrpcTransport( + 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_pages_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PagesGrpcAsyncIOTransport( + 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.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) +def test_pages_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.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) +def test_pages_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_type_path(): + project = "squid" + location = "clam" + agent = "whelk" + entity_type = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + actual = PagesClient.entity_type_path(project, location, agent, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "entity_type": "mussel", + } + path = PagesClient.entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_entity_type_path(path) + assert expected == actual + +def test_flow_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + flow = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = PagesClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "flow": "octopus", + } + path = PagesClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_flow_path(path) + assert expected == actual + +def test_intent_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + intent = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = PagesClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "intent": "abalone", + } + path = PagesClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_intent_path(path) + assert expected == actual + +def test_page_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + page = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + actual = PagesClient.page_path(project, location, agent, flow, page) + assert expected == actual + + +def test_parse_page_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "flow": "winkle", + "page": "nautilus", + } + path = PagesClient.page_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_page_path(path) + assert expected == actual + +def test_transition_route_group_path(): + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" + transition_route_group = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + actual = PagesClient.transition_route_group_path(project, location, agent, flow, transition_route_group) + assert expected == actual + + +def test_parse_transition_route_group_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "transition_route_group": "mussel", + } + path = PagesClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_transition_route_group_path(path) + assert expected == actual + +def test_webhook_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = PagesClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", + } + path = PagesClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PagesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = PagesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = PagesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = PagesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PagesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = PagesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = PagesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = PagesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.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 = PagesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = PagesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PagesClient.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.PagesTransport, '_prep_wrapped_messages') as prep: + client = PagesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PagesTransport, '_prep_wrapped_messages') as prep: + transport_class = PagesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py new file mode 100644 index 00000000..edd873cf --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py @@ -0,0 +1,2419 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.security_settings_service import SecuritySettingsServiceAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import SecuritySettingsServiceClient +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import pagers +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import transports +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import security_settings +from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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 SecuritySettingsServiceClient._get_default_mtls_endpoint(None) is None + assert SecuritySettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecuritySettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecuritySettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecuritySettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecuritySettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SecuritySettingsServiceClient, + SecuritySettingsServiceAsyncClient, +]) +def test_security_settings_service_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", [ + SecuritySettingsServiceClient, + SecuritySettingsServiceAsyncClient, +]) +def test_security_settings_service_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_security_settings_service_client_get_transport_class(): + transport = SecuritySettingsServiceClient.get_transport_class() + available_transports = [ + transports.SecuritySettingsServiceGrpcTransport, + ] + assert transport in available_transports + + transport = SecuritySettingsServiceClient.get_transport_class("grpc") + assert transport == transports.SecuritySettingsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), + (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SecuritySettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceClient)) +@mock.patch.object(SecuritySettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceAsyncClient)) +def test_security_settings_service_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(SecuritySettingsServiceClient, '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(SecuritySettingsServiceClient, '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", [ + (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc", "true"), + (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc", "false"), + (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SecuritySettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceClient)) +@mock.patch.object(SecuritySettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_settings_service_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", [ + (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), + (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_settings_service_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", [ + (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), + (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_settings_service_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_security_settings_service_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecuritySettingsServiceClient( + 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_security_settings(transport: str = 'grpc', request_type=gcdc_security_settings.CreateSecuritySettingsRequest): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + retention_window_days=2271, + ) + response = client.create_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +def test_create_security_settings_from_dict(): + test_create_security_settings(request_type=dict) + + +def test_create_security_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecuritySettingsServiceClient( + credentials=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_security_settings), + '__call__') as call: + client.create_security_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() + + +@pytest.mark.asyncio +async def test_create_security_settings_async(transport: str = 'grpc_asyncio', request_type=gcdc_security_settings.CreateSecuritySettingsRequest): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + )) + response = await client.create_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +@pytest.mark.asyncio +async def test_create_security_settings_async_from_dict(): + await test_create_security_settings_async(request_type=dict) + + +def test_create_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_security_settings.CreateSecuritySettingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), + '__call__') as call: + call.return_value = gcdc_security_settings.SecuritySettings() + client.create_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_security_settings.CreateSecuritySettingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) + await client.create_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_security_settings( + parent='parent_value', + security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') + + +def test_create_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=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_security_settings( + gcdc_security_settings.CreateSecuritySettingsRequest(), + parent='parent_value', + security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_security_settings( + parent='parent_value', + security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') + + +@pytest.mark.asyncio +async def test_create_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_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_security_settings( + gcdc_security_settings.CreateSecuritySettingsRequest(), + parent='parent_value', + security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), + ) + + +def test_get_security_settings(transport: str = 'grpc', request_type=security_settings.GetSecuritySettingsRequest): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + retention_window_days=2271, + ) + response = client.get_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.GetSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +def test_get_security_settings_from_dict(): + test_get_security_settings(request_type=dict) + + +def test_get_security_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecuritySettingsServiceClient( + credentials=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_security_settings), + '__call__') as call: + client.get_security_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.GetSecuritySettingsRequest() + + +@pytest.mark.asyncio +async def test_get_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.GetSecuritySettingsRequest): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + )) + response = await client.get_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.GetSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +@pytest.mark.asyncio +async def test_get_security_settings_async_from_dict(): + await test_get_security_settings_async(request_type=dict) + + +def test_get_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.GetSecuritySettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), + '__call__') as call: + call.return_value = security_settings.SecuritySettings() + client.get_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.GetSecuritySettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings()) + await client.get_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.SecuritySettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_security_settings( + name='name_value', + ) + + # Establish that the 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_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=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_security_settings( + security_settings.GetSecuritySettingsRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.SecuritySettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_security_settings( + 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_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_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_security_settings( + security_settings.GetSecuritySettingsRequest(), + name='name_value', + ) + + +def test_update_security_settings(transport: str = 'grpc', request_type=gcdc_security_settings.UpdateSecuritySettingsRequest): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + retention_window_days=2271, + ) + response = client.update_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +def test_update_security_settings_from_dict(): + test_update_security_settings(request_type=dict) + + +def test_update_security_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecuritySettingsServiceClient( + credentials=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_security_settings), + '__call__') as call: + client.update_security_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() + + +@pytest.mark.asyncio +async def test_update_security_settings_async(transport: str = 'grpc_asyncio', request_type=gcdc_security_settings.UpdateSecuritySettingsRequest): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings( + name='name_value', + display_name='display_name_value', + redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, + redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, + inspect_template='inspect_template_value', + purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], + )) + response = await client.update_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_security_settings.SecuritySettings) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE + assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE + assert response.inspect_template == 'inspect_template_value' + assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] + + +@pytest.mark.asyncio +async def test_update_security_settings_async_from_dict(): + await test_update_security_settings_async(request_type=dict) + + +def test_update_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_security_settings.UpdateSecuritySettingsRequest() + + request.security_settings.name = 'security_settings.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), + '__call__') as call: + call.return_value = gcdc_security_settings.SecuritySettings() + client.update_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_settings.name=security_settings.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_security_settings.UpdateSecuritySettingsRequest() + + request.security_settings.name = 'security_settings.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) + await client.update_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'security_settings.name=security_settings.name/value', + ) in kw['metadata'] + + +def test_update_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_settings( + security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=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_security_settings( + gcdc_security_settings.UpdateSecuritySettingsRequest(), + security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_security_settings.SecuritySettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_settings( + security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_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_security_settings( + gcdc_security_settings.UpdateSecuritySettingsRequest(), + security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_security_settings(transport: str = 'grpc', request_type=security_settings.ListSecuritySettingsRequest): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.ListSecuritySettingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.ListSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecuritySettingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_security_settings_from_dict(): + test_list_security_settings(request_type=dict) + + +def test_list_security_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecuritySettingsServiceClient( + credentials=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_security_settings), + '__call__') as call: + client.list_security_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.ListSecuritySettingsRequest() + + +@pytest.mark.asyncio +async def test_list_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.ListSecuritySettingsRequest): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.ListSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecuritySettingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_security_settings_async_from_dict(): + await test_list_security_settings_async(request_type=dict) + + +def test_list_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.ListSecuritySettingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + call.return_value = security_settings.ListSecuritySettingsResponse() + client.list_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.ListSecuritySettingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse()) + await client.list_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.ListSecuritySettingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_security_settings( + parent='parent_value', + ) + + # Establish that the 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_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=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_security_settings( + security_settings.ListSecuritySettingsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = security_settings.ListSecuritySettingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_security_settings( + 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_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_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_security_settings( + security_settings.ListSecuritySettingsRequest(), + parent='parent_value', + ) + + +def test_list_security_settings_pager(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token='abc', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], + next_page_token='def', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + ], + next_page_token='ghi', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_security_settings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, security_settings.SecuritySettings) + for i in results) + +def test_list_security_settings_pages(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token='abc', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], + next_page_token='def', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + ], + next_page_token='ghi', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + pages = list(client.list_security_settings(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_security_settings_async_pager(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token='abc', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], + next_page_token='def', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + ], + next_page_token='ghi', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_security_settings(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, security_settings.SecuritySettings) + for i in responses) + +@pytest.mark.asyncio +async def test_list_security_settings_async_pages(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_security_settings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + next_page_token='abc', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[], + next_page_token='def', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + ], + next_page_token='ghi', + ), + security_settings.ListSecuritySettingsResponse( + security_settings=[ + security_settings.SecuritySettings(), + security_settings.SecuritySettings(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_security_settings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_delete_security_settings(transport: str = 'grpc', request_type=security_settings.DeleteSecuritySettingsRequest): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.DeleteSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_security_settings_from_dict(): + test_delete_security_settings(request_type=dict) + + +def test_delete_security_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecuritySettingsServiceClient( + credentials=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_security_settings), + '__call__') as call: + client.delete_security_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.DeleteSecuritySettingsRequest() + + +@pytest.mark.asyncio +async def test_delete_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.DeleteSecuritySettingsRequest): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_security_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == security_settings.DeleteSecuritySettingsRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_security_settings_async_from_dict(): + await test_delete_security_settings_async(request_type=dict) + + +def test_delete_security_settings_field_headers(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.DeleteSecuritySettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), + '__call__') as call: + call.return_value = None + client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_security_settings_field_headers_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = security_settings.DeleteSecuritySettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_security_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_security_settings_flattened(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), + '__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_security_settings( + 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_security_settings_flattened_error(): + client = SecuritySettingsServiceClient( + credentials=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_security_settings( + security_settings.DeleteSecuritySettingsRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_security_settings_flattened_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_security_settings), + '__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_security_settings( + 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_security_settings_flattened_error_async(): + client = SecuritySettingsServiceAsyncClient( + credentials=ga_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_security_settings( + security_settings.DeleteSecuritySettingsRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecuritySettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecuritySettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecuritySettingsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecuritySettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecuritySettingsServiceGrpcTransport, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, +]) +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 = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecuritySettingsServiceGrpcTransport, + ) + +def test_security_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecuritySettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecuritySettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_security_settings', + 'get_security_settings', + 'update_security_settings', + 'list_security_settings', + 'delete_security_settings', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_security_settings_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecuritySettingsServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_security_settings_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecuritySettingsServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_security_settings_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecuritySettingsServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_security_settings_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SecuritySettingsServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_security_settings_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SecuritySettingsServiceClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecuritySettingsServiceGrpcTransport, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_security_settings_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecuritySettingsServiceGrpcTransport, + transports.SecuritySettingsServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_security_settings_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_security_settings_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_security_settings_service_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_security_settings_service_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) +def test_security_settings_service_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_security_settings_service_host_no_port(): + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_security_settings_service_host_with_port(): + client = SecuritySettingsServiceClient( + 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_security_settings_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecuritySettingsServiceGrpcTransport( + 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_security_settings_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( + 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.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) +def test_security_settings_service_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.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) +def test_security_settings_service_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_security_settings_path(): + project = "squid" + location = "clam" + security_settings = "whelk" + expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) + actual = SecuritySettingsServiceClient.security_settings_path(project, location, security_settings) + assert expected == actual + + +def test_parse_security_settings_path(): + expected = { + "project": "octopus", + "location": "oyster", + "security_settings": "nudibranch", + } + path = SecuritySettingsServiceClient.security_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_security_settings_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecuritySettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SecuritySettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecuritySettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SecuritySettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecuritySettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SecuritySettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SecuritySettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SecuritySettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.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 = SecuritySettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SecuritySettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecuritySettingsServiceClient.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.SecuritySettingsServiceTransport, '_prep_wrapped_messages') as prep: + client = SecuritySettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecuritySettingsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SecuritySettingsServiceClient.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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py new file mode 100644 index 00000000..e149c587 --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py @@ -0,0 +1,2373 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.session_entity_types import SessionEntityTypesAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import SessionEntityTypesClient +from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import pagers +from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import transports +from google.cloud.dialogflowcx_v3beta1.services.session_entity_types.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.session_entity_types.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import entity_type +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_session_entity_type +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3beta1.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=gcdc_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 = gcdc_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + ) + response = client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +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] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_create_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + )) + response = await client.create_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_session_entity_type.SessionEntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_session_entity_type( + parent='parent_value', + session_entity_type=gcdc_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 == gcdc_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( + gcdc_session_entity_type.CreateSessionEntityTypeRequest(), + parent='parent_value', + session_entity_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( + gcdc_session_entity_type.CreateSessionEntityTypeRequest(), + parent='parent_value', + session_entity_type=gcdc_session_entity_type.SessionEntityType(name='name_value'), + ) + + +def test_update_session_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + ) + response = client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +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] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + + +@pytest.mark.asyncio +async def test_update_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_session_entity_type.SessionEntityType( + name='name_value', + entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, + )) + response = await client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_session_entity_type.SessionEntityType) + assert response.name == 'name_value' + assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE + + +@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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + + request.session_entity_type.name = 'session_entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + call.return_value = gcdc_session_entity_type.SessionEntityType() + client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + + request.session_entity_type.name = 'session_entity_type.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_session_entity_type), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_session_entity_type.SessionEntityType()) + await client.update_session_entity_type(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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 = gcdc_session_entity_type.SessionEntityType() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_session_entity_type( + session_entity_type=gcdc_session_entity_type.SessionEntityType(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].session_entity_type == gcdc_session_entity_type.SessionEntityType(name='name_value') + assert args[0].update_mask == field_mask_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( + gcdc_session_entity_type.UpdateSessionEntityTypeRequest(), + session_entity_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( + gcdc_session_entity_type.UpdateSessionEntityTypeRequest(), + session_entity_type=gcdc_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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_session_entity_types_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionEntityTypesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + 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.dialogflowcx_v3beta1.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" + location = "clam" + agent = "whelk" + session = "octopus" + entity_type = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, session=session, entity_type=entity_type, ) + actual = SessionEntityTypesClient.session_entity_type_path(project, location, agent, session, entity_type) + assert expected == actual + + +def test_parse_session_entity_type_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "session": "winkle", + "entity_type": "nautilus", + } + 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 = "scallop" + 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": "abalone", + } + 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 = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = SessionEntityTypesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + 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 = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SessionEntityTypesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + 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 = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = SessionEntityTypesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + 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": "winkle", + "location": "nautilus", + } + 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py new file mode 100644 index 00000000..42799a8d --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py @@ -0,0 +1,1708 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.sessions import SessionsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.sessions import SessionsClient +from google.cloud.dialogflowcx_v3beta1.services.sessions import transports +from google.cloud.dialogflowcx_v3beta1.services.sessions.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.sessions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import audio_config +from google.cloud.dialogflowcx_v3beta1.types import entity_type +from google.cloud.dialogflowcx_v3beta1.types import intent +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import session +from google.cloud.dialogflowcx_v3beta1.types import session_entity_type +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # 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.dialogflowcx_v3beta1.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=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 = session.DetectIntentResponse( + response_id='response_id_value', + output_audio=b'output_audio_blob', + ) + response = client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session.DetectIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.DetectIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +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] == session.DetectIntentRequest() + + +@pytest.mark.asyncio +async def test_detect_intent_async(transport: str = 'grpc_asyncio', request_type=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(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] == session.DetectIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.DetectIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +@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 = session.DetectIntentRequest() + + request.session = 'session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.detect_intent), + '__call__') as call: + call.return_value = session.DetectIntentResponse() + client.detect_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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 = 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(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_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_match_intent(transport: str = 'grpc', request_type=session.MatchIntentRequest): + 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.match_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session.MatchIntentResponse( + text='text_value', + ) + response = client.match_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session.MatchIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.MatchIntentResponse) + + +def test_match_intent_from_dict(): + test_match_intent(request_type=dict) + + +def test_match_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.match_intent), + '__call__') as call: + client.match_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session.MatchIntentRequest() + + +@pytest.mark.asyncio +async def test_match_intent_async(transport: str = 'grpc_asyncio', request_type=session.MatchIntentRequest): + 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.match_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session.MatchIntentResponse( + )) + response = await client.match_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == session.MatchIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.MatchIntentResponse) + + +@pytest.mark.asyncio +async def test_match_intent_async_from_dict(): + await test_match_intent_async(request_type=dict) + + +def test_match_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 = session.MatchIntentRequest() + + request.session = 'session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.match_intent), + '__call__') as call: + call.return_value = session.MatchIntentResponse() + client.match_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_match_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 = session.MatchIntentRequest() + + request.session = 'session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.match_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session.MatchIntentResponse()) + await client.match_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_fulfill_intent(transport: str = 'grpc', request_type=session.FulfillIntentRequest): + 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.fulfill_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = session.FulfillIntentResponse( + response_id='response_id_value', + output_audio=b'output_audio_blob', + ) + response = client.fulfill_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == session.FulfillIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.FulfillIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +def test_fulfill_intent_from_dict(): + test_fulfill_intent(request_type=dict) + + +def test_fulfill_intent_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SessionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fulfill_intent), + '__call__') as call: + client.fulfill_intent() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session.FulfillIntentRequest() + + +@pytest.mark.asyncio +async def test_fulfill_intent_async(transport: str = 'grpc_asyncio', request_type=session.FulfillIntentRequest): + 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.fulfill_intent), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session.FulfillIntentResponse( + response_id='response_id_value', + output_audio=b'output_audio_blob', + )) + response = await client.fulfill_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == session.FulfillIntentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, session.FulfillIntentResponse) + assert response.response_id == 'response_id_value' + assert response.output_audio == b'output_audio_blob' + + +@pytest.mark.asyncio +async def test_fulfill_intent_async_from_dict(): + await test_fulfill_intent_async(request_type=dict) + + +def test_fulfill_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 = session.FulfillIntentRequest() + + request.match_intent_request.session = 'match_intent_request.session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fulfill_intent), + '__call__') as call: + call.return_value = session.FulfillIntentResponse() + client.fulfill_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'match_intent_request.session=match_intent_request.session/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_fulfill_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 = session.FulfillIntentRequest() + + request.match_intent_request.session = 'match_intent_request.session/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fulfill_intent), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session.FulfillIntentResponse()) + await client.fulfill_intent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'match_intent_request.session=match_intent_request.session/value', + ) in kw['metadata'] + + +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.dialogflowcx_v3beta1.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', + 'match_intent', + 'fulfill_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.dialogflowcx_v3beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_sessions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (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.dialogflowcx_v3beta1.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_entity_type_path(): + project = "squid" + location = "clam" + agent = "whelk" + entity_type = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + actual = SessionsClient.entity_type_path(project, location, agent, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "entity_type": "mussel", + } + path = SessionsClient.entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_entity_type_path(path) + assert expected == actual + +def test_flow_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + flow = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = SessionsClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "flow": "octopus", + } + path = SessionsClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_flow_path(path) + assert expected == actual + +def test_intent_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + intent = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = SessionsClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "intent": "abalone", + } + path = SessionsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_intent_path(path) + assert expected == actual + +def test_page_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + page = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + actual = SessionsClient.page_path(project, location, agent, flow, page) + assert expected == actual + + +def test_parse_page_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "flow": "winkle", + "page": "nautilus", + } + path = SessionsClient.page_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_page_path(path) + assert expected == actual + +def test_session_path(): + project = "scallop" + location = "abalone" + agent = "squid" + session = "clam" + expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format(project=project, location=location, agent=agent, session=session, ) + actual = SessionsClient.session_path(project, location, agent, session) + assert expected == actual + + +def test_parse_session_path(): + expected = { + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "session": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + agent = "winkle" + session = "nautilus" + entity_type = "scallop" + expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, session=session, entity_type=entity_type, ) + actual = SessionsClient.session_entity_type_path(project, location, agent, session, entity_type) + assert expected == actual + + +def test_parse_session_entity_type_path(): + expected = { + "project": "abalone", + "location": "squid", + "agent": "clam", + "session": "whelk", + "entity_type": "octopus", + } + 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_transition_route_group_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + flow = "mussel" + transition_route_group = "winkle" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + actual = SessionsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) + assert expected == actual + + +def test_parse_transition_route_group_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "agent": "abalone", + "flow": "squid", + "transition_route_group": "clam", + } + path = SessionsClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_transition_route_group_path(path) + assert expected == actual + +def test_webhook_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + webhook = "nudibranch" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = SessionsClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "webhook": "nautilus", + } + path = SessionsClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = SessionsClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + 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": "abalone", + } + 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 = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = SessionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + 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 = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SessionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + 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 = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = SessionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + 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": "winkle", + "location": "nautilus", + } + 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py new file mode 100644 index 00000000..a0fb6bc1 --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py @@ -0,0 +1,4061 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.test_cases import TestCasesAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.test_cases import TestCasesClient +from google.cloud.dialogflowcx_v3beta1.services.test_cases import pagers +from google.cloud.dialogflowcx_v3beta1.services.test_cases import transports +from google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import audio_config +from google.cloud.dialogflowcx_v3beta1.types import fulfillment +from google.cloud.dialogflowcx_v3beta1.types import intent +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import response_message +from google.cloud.dialogflowcx_v3beta1.types import session +from google.cloud.dialogflowcx_v3beta1.types import test_case +from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case +from google.longrunning import operations_pb2 +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 struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) + +def client_cert_source_callback(): + 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 TestCasesClient._get_default_mtls_endpoint(None) is None + assert TestCasesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TestCasesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TestCasesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TestCasesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TestCasesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + TestCasesClient, + TestCasesAsyncClient, +]) +def test_test_cases_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", [ + TestCasesClient, + TestCasesAsyncClient, +]) +def test_test_cases_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_test_cases_client_get_transport_class(): + transport = TestCasesClient.get_transport_class() + available_transports = [ + transports.TestCasesGrpcTransport, + ] + assert transport in available_transports + + transport = TestCasesClient.get_transport_class("grpc") + assert transport == transports.TestCasesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), + (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(TestCasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesClient)) +@mock.patch.object(TestCasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesAsyncClient)) +def test_test_cases_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(TestCasesClient, '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(TestCasesClient, '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", [ + (TestCasesClient, transports.TestCasesGrpcTransport, "grpc", "true"), + (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TestCasesClient, transports.TestCasesGrpcTransport, "grpc", "false"), + (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(TestCasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesClient)) +@mock.patch.object(TestCasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_test_cases_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", [ + (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), + (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_test_cases_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", [ + (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), + (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_test_cases_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_test_cases_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TestCasesClient( + 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_test_cases(transport: str = 'grpc', request_type=test_case.ListTestCasesRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCasesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTestCasesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_test_cases_from_dict(): + test_list_test_cases(request_type=dict) + + +def test_list_test_cases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_cases), + '__call__') as call: + client.list_test_cases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCasesRequest() + + +@pytest.mark.asyncio +async def test_list_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ListTestCasesRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTestCasesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_test_cases_async_from_dict(): + await test_list_test_cases_async(request_type=dict) + + +def test_list_test_cases_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ListTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + call.return_value = test_case.ListTestCasesResponse() + client.list_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_cases_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ListTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse()) + await client.list_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_cases_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCasesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_test_cases( + parent='parent_value', + ) + + # Establish that the 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_test_cases_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_test_cases( + test_case.ListTestCasesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_test_cases_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCasesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_test_cases( + 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_test_cases_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_test_cases( + test_case.ListTestCasesRequest(), + parent='parent_value', + ) + + +def test_list_test_cases_pager(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + test_case.TestCase(), + ], + next_page_token='abc', + ), + test_case.ListTestCasesResponse( + test_cases=[], + next_page_token='def', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + ], + next_page_token='ghi', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_test_cases(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, test_case.TestCase) + for i in results) + +def test_list_test_cases_pages(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + test_case.TestCase(), + ], + next_page_token='abc', + ), + test_case.ListTestCasesResponse( + test_cases=[], + next_page_token='def', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + ], + next_page_token='ghi', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + ], + ), + RuntimeError, + ) + pages = list(client.list_test_cases(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_test_cases_async_pager(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + test_case.TestCase(), + ], + next_page_token='abc', + ), + test_case.ListTestCasesResponse( + test_cases=[], + next_page_token='def', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + ], + next_page_token='ghi', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_test_cases(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, test_case.TestCase) + for i in responses) + +@pytest.mark.asyncio +async def test_list_test_cases_async_pages(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_cases), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + test_case.TestCase(), + ], + next_page_token='abc', + ), + test_case.ListTestCasesResponse( + test_cases=[], + next_page_token='def', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + ], + next_page_token='ghi', + ), + test_case.ListTestCasesResponse( + test_cases=[ + test_case.TestCase(), + test_case.TestCase(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_test_cases(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_batch_delete_test_cases(transport: str = 'grpc', request_type=test_case.BatchDeleteTestCasesRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.batch_delete_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchDeleteTestCasesRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_batch_delete_test_cases_from_dict(): + test_batch_delete_test_cases(request_type=dict) + + +def test_batch_delete_test_cases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_cases), + '__call__') as call: + client.batch_delete_test_cases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchDeleteTestCasesRequest() + + +@pytest.mark.asyncio +async def test_batch_delete_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.BatchDeleteTestCasesRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.batch_delete_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchDeleteTestCasesRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_batch_delete_test_cases_async_from_dict(): + await test_batch_delete_test_cases_async(request_type=dict) + + +def test_batch_delete_test_cases_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.BatchDeleteTestCasesRequest() + + 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_test_cases), + '__call__') as call: + call.return_value = None + client.batch_delete_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_cases_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.BatchDeleteTestCasesRequest() + + 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_test_cases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.batch_delete_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_cases_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_test_cases), + '__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.batch_delete_test_cases( + 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_delete_test_cases_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_test_cases( + test_case.BatchDeleteTestCasesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_batch_delete_test_cases_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_test_cases), + '__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.batch_delete_test_cases( + 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_delete_test_cases_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_delete_test_cases( + test_case.BatchDeleteTestCasesRequest(), + parent='parent_value', + ) + + +def test_get_test_case(transport: str = 'grpc', request_type=test_case.GetTestCaseRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + ) + response = client.get_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +def test_get_test_case_from_dict(): + test_get_test_case(request_type=dict) + + +def test_get_test_case_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + client.get_test_case() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseRequest() + + +@pytest.mark.asyncio +async def test_get_test_case_async(transport: str = 'grpc_asyncio', request_type=test_case.GetTestCaseRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + )) + response = await client.get_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +@pytest.mark.asyncio +async def test_get_test_case_async_from_dict(): + await test_get_test_case_async(request_type=dict) + + +def test_get_test_case_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.GetTestCaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + call.return_value = test_case.TestCase() + client.get_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_test_case_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.GetTestCaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase()) + await client.get_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_test_case_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_test_case( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_test_case_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_test_case( + test_case.GetTestCaseRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_test_case_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_test_case( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_test_case_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_test_case( + test_case.GetTestCaseRequest(), + name='name_value', + ) + + +def test_create_test_case(transport: str = 'grpc', request_type=gcdc_test_case.CreateTestCaseRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + ) + response = client.create_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.CreateTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +def test_create_test_case_from_dict(): + test_create_test_case(request_type=dict) + + +def test_create_test_case_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_case), + '__call__') as call: + client.create_test_case() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.CreateTestCaseRequest() + + +@pytest.mark.asyncio +async def test_create_test_case_async(transport: str = 'grpc_asyncio', request_type=gcdc_test_case.CreateTestCaseRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + )) + response = await client.create_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.CreateTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +@pytest.mark.asyncio +async def test_create_test_case_async_from_dict(): + await test_create_test_case_async(request_type=dict) + + +def test_create_test_case_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_test_case.CreateTestCaseRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + call.return_value = gcdc_test_case.TestCase() + client.create_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_case_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_test_case.CreateTestCaseRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) + await client.create_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_case_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_test_case( + parent='parent_value', + test_case=gcdc_test_case.TestCase(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].test_case == gcdc_test_case.TestCase(name='name_value') + + +def test_create_test_case_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_test_case( + gcdc_test_case.CreateTestCaseRequest(), + parent='parent_value', + test_case=gcdc_test_case.TestCase(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_test_case_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_test_case( + parent='parent_value', + test_case=gcdc_test_case.TestCase(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].test_case == gcdc_test_case.TestCase(name='name_value') + + +@pytest.mark.asyncio +async def test_create_test_case_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_test_case( + gcdc_test_case.CreateTestCaseRequest(), + parent='parent_value', + test_case=gcdc_test_case.TestCase(name='name_value'), + ) + + +def test_update_test_case(transport: str = 'grpc', request_type=gcdc_test_case.UpdateTestCaseRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + ) + response = client.update_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.UpdateTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +def test_update_test_case_from_dict(): + test_update_test_case(request_type=dict) + + +def test_update_test_case_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_case), + '__call__') as call: + client.update_test_case() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.UpdateTestCaseRequest() + + +@pytest.mark.asyncio +async def test_update_test_case_async(transport: str = 'grpc_asyncio', request_type=gcdc_test_case.UpdateTestCaseRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase( + name='name_value', + tags=['tags_value'], + display_name='display_name_value', + notes='notes_value', + )) + response = await client.update_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_test_case.UpdateTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_test_case.TestCase) + assert response.name == 'name_value' + assert response.tags == ['tags_value'] + assert response.display_name == 'display_name_value' + assert response.notes == 'notes_value' + + +@pytest.mark.asyncio +async def test_update_test_case_async_from_dict(): + await test_update_test_case_async(request_type=dict) + + +def test_update_test_case_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_test_case.UpdateTestCaseRequest() + + request.test_case.name = 'test_case.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + call.return_value = gcdc_test_case.TestCase() + client.update_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'test_case.name=test_case.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_test_case_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_test_case.UpdateTestCaseRequest() + + request.test_case.name = 'test_case.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) + await client.update_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'test_case.name=test_case.name/value', + ) in kw['metadata'] + + +def test_update_test_case_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_test_case( + test_case=gcdc_test_case.TestCase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].test_case == gcdc_test_case.TestCase(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_test_case_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_test_case( + gcdc_test_case.UpdateTestCaseRequest(), + test_case=gcdc_test_case.TestCase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_test_case_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_test_case.TestCase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_test_case( + test_case=gcdc_test_case.TestCase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].test_case == gcdc_test_case.TestCase(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_test_case_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_test_case( + gcdc_test_case.UpdateTestCaseRequest(), + test_case=gcdc_test_case.TestCase(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_run_test_case(transport: str = 'grpc', request_type=test_case.RunTestCaseRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_test_case), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.RunTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_test_case_from_dict(): + test_run_test_case(request_type=dict) + + +def test_run_test_case_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_test_case), + '__call__') as call: + client.run_test_case() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.RunTestCaseRequest() + + +@pytest.mark.asyncio +async def test_run_test_case_async(transport: str = 'grpc_asyncio', request_type=test_case.RunTestCaseRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_test_case), + '__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.run_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.RunTestCaseRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_test_case_async_from_dict(): + await test_run_test_case_async(request_type=dict) + + +def test_run_test_case_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.RunTestCaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_test_case), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_run_test_case_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.RunTestCaseRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_test_case), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_test_case(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_batch_run_test_cases(transport: str = 'grpc', request_type=test_case.BatchRunTestCasesRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.batch_run_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchRunTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_run_test_cases_from_dict(): + test_batch_run_test_cases(request_type=dict) + + +def test_batch_run_test_cases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_run_test_cases), + '__call__') as call: + client.batch_run_test_cases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchRunTestCasesRequest() + + +@pytest.mark.asyncio +async def test_batch_run_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.BatchRunTestCasesRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_test_cases), + '__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_run_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.BatchRunTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_run_test_cases_async_from_dict(): + await test_batch_run_test_cases_async(request_type=dict) + + +def test_batch_run_test_cases_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.BatchRunTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_test_cases), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.batch_run_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_run_test_cases_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.BatchRunTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_run_test_cases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.batch_run_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_calculate_coverage(transport: str = 'grpc', request_type=test_case.CalculateCoverageRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.calculate_coverage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.CalculateCoverageResponse( + agent='agent_value', + intent_coverage=test_case.IntentCoverage(intents=[test_case.IntentCoverage.Intent(intent='intent_value')]), + ) + response = client.calculate_coverage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.CalculateCoverageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.CalculateCoverageResponse) + assert response.agent == 'agent_value' + + +def test_calculate_coverage_from_dict(): + test_calculate_coverage(request_type=dict) + + +def test_calculate_coverage_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.calculate_coverage), + '__call__') as call: + client.calculate_coverage() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.CalculateCoverageRequest() + + +@pytest.mark.asyncio +async def test_calculate_coverage_async(transport: str = 'grpc_asyncio', request_type=test_case.CalculateCoverageRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.calculate_coverage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.CalculateCoverageResponse( + agent='agent_value', + )) + response = await client.calculate_coverage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.CalculateCoverageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.CalculateCoverageResponse) + assert response.agent == 'agent_value' + + +@pytest.mark.asyncio +async def test_calculate_coverage_async_from_dict(): + await test_calculate_coverage_async(request_type=dict) + + +def test_calculate_coverage_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.CalculateCoverageRequest() + + request.agent = 'agent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.calculate_coverage), + '__call__') as call: + call.return_value = test_case.CalculateCoverageResponse() + client.calculate_coverage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=agent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_calculate_coverage_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.CalculateCoverageRequest() + + request.agent = 'agent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.calculate_coverage), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.CalculateCoverageResponse()) + await client.calculate_coverage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'agent=agent/value', + ) in kw['metadata'] + + +def test_import_test_cases(transport: str = 'grpc', request_type=test_case.ImportTestCasesRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ImportTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_test_cases_from_dict(): + test_import_test_cases(request_type=dict) + + +def test_import_test_cases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_cases), + '__call__') as call: + client.import_test_cases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ImportTestCasesRequest() + + +@pytest.mark.asyncio +async def test_import_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ImportTestCasesRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_test_cases), + '__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_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ImportTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_test_cases_async_from_dict(): + await test_import_test_cases_async(request_type=dict) + + +def test_import_test_cases_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ImportTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_test_cases), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_cases_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ImportTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_test_cases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_cases(transport: str = 'grpc', request_type=test_case.ExportTestCasesRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_test_cases), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ExportTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_test_cases_from_dict(): + test_export_test_cases(request_type=dict) + + +def test_export_test_cases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_cases), + '__call__') as call: + client.export_test_cases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ExportTestCasesRequest() + + +@pytest.mark.asyncio +async def test_export_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ExportTestCasesRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_test_cases), + '__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_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ExportTestCasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_test_cases_async_from_dict(): + await test_export_test_cases_async(request_type=dict) + + +def test_export_test_cases_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ExportTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_test_cases), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_cases_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ExportTestCasesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_test_cases), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_test_cases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_case_results(transport: str = 'grpc', request_type=test_case.ListTestCaseResultsRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCaseResultsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_test_case_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCaseResultsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTestCaseResultsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_test_case_results_from_dict(): + test_list_test_case_results(request_type=dict) + + +def test_list_test_case_results_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=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_test_case_results), + '__call__') as call: + client.list_test_case_results() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCaseResultsRequest() + + +@pytest.mark.asyncio +async def test_list_test_case_results_async(transport: str = 'grpc_asyncio', request_type=test_case.ListTestCaseResultsRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_test_case_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.ListTestCaseResultsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTestCaseResultsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_test_case_results_async_from_dict(): + await test_list_test_case_results_async(request_type=dict) + + +def test_list_test_case_results_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ListTestCaseResultsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + call.return_value = test_case.ListTestCaseResultsResponse() + client.list_test_case_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_test_case_results_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.ListTestCaseResultsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse()) + await client.list_test_case_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_test_case_results_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCaseResultsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_test_case_results( + parent='parent_value', + ) + + # Establish that the 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_test_case_results_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_test_case_results( + test_case.ListTestCaseResultsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_test_case_results_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.ListTestCaseResultsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_test_case_results( + 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_test_case_results_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_test_case_results( + test_case.ListTestCaseResultsRequest(), + parent='parent_value', + ) + + +def test_list_test_case_results_pager(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + next_page_token='abc', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[], + next_page_token='def', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + ], + next_page_token='ghi', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_test_case_results(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, test_case.TestCaseResult) + for i in results) + +def test_list_test_case_results_pages(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + next_page_token='abc', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[], + next_page_token='def', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + ], + next_page_token='ghi', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_test_case_results(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_test_case_results_async_pager(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + next_page_token='abc', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[], + next_page_token='def', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + ], + next_page_token='ghi', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_test_case_results(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, test_case.TestCaseResult) + for i in responses) + +@pytest.mark.asyncio +async def test_list_test_case_results_async_pages(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_test_case_results), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + next_page_token='abc', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[], + next_page_token='def', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + ], + next_page_token='ghi', + ), + test_case.ListTestCaseResultsResponse( + test_case_results=[ + test_case.TestCaseResult(), + test_case.TestCaseResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_test_case_results(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_test_case_result(transport: str = 'grpc', request_type=test_case.GetTestCaseResultRequest): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult( + name='name_value', + environment='environment_value', + test_result=test_case.TestResult.PASSED, + ) + response = client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCaseResult) + assert response.name == 'name_value' + assert response.environment == 'environment_value' + assert response.test_result == test_case.TestResult.PASSED + + +def test_get_test_case_result_from_dict(): + test_get_test_case_result(request_type=dict) + + +def test_get_test_case_result_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + client.get_test_case_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + +@pytest.mark.asyncio +async def test_get_test_case_result_async(transport: str = 'grpc_asyncio', request_type=test_case.GetTestCaseResultRequest): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult( + name='name_value', + environment='environment_value', + test_result=test_case.TestResult.PASSED, + )) + response = await client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCaseResult) + assert response.name == 'name_value' + assert response.environment == 'environment_value' + assert response.test_result == test_case.TestResult.PASSED + + +@pytest.mark.asyncio +async def test_get_test_case_result_async_from_dict(): + await test_get_test_case_result_async(request_type=dict) + + +def test_get_test_case_result_field_headers(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.GetTestCaseResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + call.return_value = test_case.TestCaseResult() + client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_test_case_result_field_headers_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = test_case.GetTestCaseResultRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult()) + await client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_test_case_result_flattened(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_test_case_result( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +def test_get_test_case_result_flattened_error(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_test_case_result( + test_case.GetTestCaseResultRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_test_case_result_flattened_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_test_case_result( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_test_case_result_flattened_error_async(): + client = TestCasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_test_case_result( + test_case.GetTestCaseResultRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TestCasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TestCasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TestCasesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TestCasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TestCasesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TestCasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TestCasesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TestCasesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TestCasesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TestCasesGrpcTransport, + transports.TestCasesGrpcAsyncIOTransport, +]) +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 = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TestCasesGrpcTransport, + ) + +def test_test_cases_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TestCasesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_test_cases_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TestCasesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_test_cases', + 'batch_delete_test_cases', + 'get_test_case', + 'create_test_case', + 'update_test_case', + 'run_test_case', + 'batch_run_test_cases', + 'calculate_coverage', + 'import_test_cases', + 'export_test_cases', + 'list_test_case_results', + 'get_test_case_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_test_cases_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TestCasesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_test_cases_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TestCasesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_test_cases_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TestCasesTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_test_cases_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TestCasesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_test_cases_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TestCasesClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TestCasesGrpcTransport, + transports.TestCasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_test_cases_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TestCasesGrpcTransport, + transports.TestCasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_test_cases_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_test_cases_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_test_cases_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_test_cases_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) +def test_test_cases_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = 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_test_cases_host_no_port(): + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_test_cases_host_with_port(): + client = TestCasesClient( + 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_test_cases_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TestCasesGrpcTransport( + 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_test_cases_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TestCasesGrpcAsyncIOTransport( + 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.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) +def test_test_cases_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.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) +def test_test_cases_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_test_cases_grpc_lro_client(): + client = TestCasesClient( + 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_test_cases_grpc_lro_async_client(): + client = TestCasesAsyncClient( + 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" + location = "clam" + agent = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) + actual = TestCasesClient.agent_path(project, location, agent) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + } + path = TestCasesClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_agent_path(path) + assert expected == actual + +def test_entity_type_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + entity_type = "nautilus" + expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) + actual = TestCasesClient.entity_type_path(project, location, agent, entity_type) + assert expected == actual + + +def test_parse_entity_type_path(): + expected = { + "project": "scallop", + "location": "abalone", + "agent": "squid", + "entity_type": "clam", + } + path = TestCasesClient.entity_type_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_entity_type_path(path) + assert expected == actual + +def test_environment_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + environment = "nudibranch" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) + actual = TestCasesClient.environment_path(project, location, agent, environment) + assert expected == actual + + +def test_parse_environment_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "agent": "winkle", + "environment": "nautilus", + } + path = TestCasesClient.environment_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_environment_path(path) + assert expected == actual + +def test_flow_path(): + project = "scallop" + location = "abalone" + agent = "squid" + flow = "clam" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = TestCasesClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "flow": "nudibranch", + } + path = TestCasesClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_flow_path(path) + assert expected == actual + +def test_intent_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + intent = "nautilus" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = TestCasesClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "scallop", + "location": "abalone", + "agent": "squid", + "intent": "clam", + } + path = TestCasesClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_intent_path(path) + assert expected == actual + +def test_page_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + flow = "nudibranch" + page = "cuttlefish" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + actual = TestCasesClient.page_path(project, location, agent, flow, page) + assert expected == actual + + +def test_parse_page_path(): + expected = { + "project": "mussel", + "location": "winkle", + "agent": "nautilus", + "flow": "scallop", + "page": "abalone", + } + path = TestCasesClient.page_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_page_path(path) + assert expected == actual + +def test_test_case_path(): + project = "squid" + location = "clam" + agent = "whelk" + test_case = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(project=project, location=location, agent=agent, test_case=test_case, ) + actual = TestCasesClient.test_case_path(project, location, agent, test_case) + assert expected == actual + + +def test_parse_test_case_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "test_case": "mussel", + } + path = TestCasesClient.test_case_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_test_case_path(path) + assert expected == actual + +def test_test_case_result_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + test_case = "abalone" + result = "squid" + expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) + actual = TestCasesClient.test_case_result_path(project, location, agent, test_case, result) + assert expected == actual + + +def test_parse_test_case_result_path(): + expected = { + "project": "clam", + "location": "whelk", + "agent": "octopus", + "test_case": "oyster", + "result": "nudibranch", + } + path = TestCasesClient.test_case_result_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_test_case_result_path(path) + assert expected == actual + +def test_transition_route_group_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + flow = "nautilus" + transition_route_group = "scallop" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + actual = TestCasesClient.transition_route_group_path(project, location, agent, flow, transition_route_group) + assert expected == actual + + +def test_parse_transition_route_group_path(): + expected = { + "project": "abalone", + "location": "squid", + "agent": "clam", + "flow": "whelk", + "transition_route_group": "octopus", + } + path = TestCasesClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_transition_route_group_path(path) + assert expected == actual + +def test_webhook_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + webhook = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = TestCasesClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "webhook": "abalone", + } + path = TestCasesClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TestCasesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = TestCasesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = TestCasesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = TestCasesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TestCasesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = TestCasesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = TestCasesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = TestCasesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = TestCasesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = TestCasesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TestCasesClient.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.TestCasesTransport, '_prep_wrapped_messages') as prep: + client = TestCasesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TestCasesTransport, '_prep_wrapped_messages') as prep: + transport_class = TestCasesClient.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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py new file mode 100644 index 00000000..90fbb52c --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py @@ -0,0 +1,2470 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.transition_route_groups import TransitionRouteGroupsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import TransitionRouteGroupsClient +from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import pagers +from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import transports +from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import fulfillment +from google.cloud.dialogflowcx_v3beta1.types import page +from google.cloud.dialogflowcx_v3beta1.types import response_message +from google.cloud.dialogflowcx_v3beta1.types import transition_route_group +from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group +from google.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 TransitionRouteGroupsClient._get_default_mtls_endpoint(None) is None + assert TransitionRouteGroupsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TransitionRouteGroupsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TransitionRouteGroupsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TransitionRouteGroupsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TransitionRouteGroupsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + TransitionRouteGroupsClient, + TransitionRouteGroupsAsyncClient, +]) +def test_transition_route_groups_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", [ + TransitionRouteGroupsClient, + TransitionRouteGroupsAsyncClient, +]) +def test_transition_route_groups_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_transition_route_groups_client_get_transport_class(): + transport = TransitionRouteGroupsClient.get_transport_class() + available_transports = [ + transports.TransitionRouteGroupsGrpcTransport, + ] + assert transport in available_transports + + transport = TransitionRouteGroupsClient.get_transport_class("grpc") + assert transport == transports.TransitionRouteGroupsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), + (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(TransitionRouteGroupsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsClient)) +@mock.patch.object(TransitionRouteGroupsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsAsyncClient)) +def test_transition_route_groups_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(TransitionRouteGroupsClient, '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(TransitionRouteGroupsClient, '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", [ + (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc", "true"), + (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc", "false"), + (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(TransitionRouteGroupsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsClient)) +@mock.patch.object(TransitionRouteGroupsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_transition_route_groups_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", [ + (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), + (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_transition_route_groups_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", [ + (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), + (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_transition_route_groups_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_transition_route_groups_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TransitionRouteGroupsClient( + 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_transition_route_groups(transport: str = 'grpc', request_type=transition_route_group.ListTransitionRouteGroupsRequest): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.ListTransitionRouteGroupsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_transition_route_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransitionRouteGroupsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_transition_route_groups_from_dict(): + test_list_transition_route_groups(request_type=dict) + + +def test_list_transition_route_groups_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TransitionRouteGroupsClient( + credentials=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_transition_route_groups), + '__call__') as call: + client.list_transition_route_groups() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() + + +@pytest.mark.asyncio +async def test_list_transition_route_groups_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.ListTransitionRouteGroupsRequest): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_transition_route_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTransitionRouteGroupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_transition_route_groups_async_from_dict(): + await test_list_transition_route_groups_async(request_type=dict) + + +def test_list_transition_route_groups_field_headers(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.ListTransitionRouteGroupsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() + client.list_transition_route_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_transition_route_groups_field_headers_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.ListTransitionRouteGroupsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse()) + await client.list_transition_route_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_transition_route_groups_flattened(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_transition_route_groups( + parent='parent_value', + ) + + # Establish that the 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_transition_route_groups_flattened_error(): + client = TransitionRouteGroupsClient( + credentials=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_transition_route_groups( + transition_route_group.ListTransitionRouteGroupsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_transition_route_groups_flattened_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_transition_route_groups( + 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_transition_route_groups_flattened_error_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_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_transition_route_groups( + transition_route_group.ListTransitionRouteGroupsRequest(), + parent='parent_value', + ) + + +def test_list_transition_route_groups_pager(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='abc', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[], + next_page_token='def', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='ghi', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_transition_route_groups(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, transition_route_group.TransitionRouteGroup) + for i in results) + +def test_list_transition_route_groups_pages(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='abc', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[], + next_page_token='def', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='ghi', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_transition_route_groups(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_transition_route_groups_async_pager(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='abc', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[], + next_page_token='def', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='ghi', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_transition_route_groups(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, transition_route_group.TransitionRouteGroup) + for i in responses) + +@pytest.mark.asyncio +async def test_list_transition_route_groups_async_pages(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_transition_route_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='abc', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[], + next_page_token='def', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + ], + next_page_token='ghi', + ), + transition_route_group.ListTransitionRouteGroupsResponse( + transition_route_groups=[ + transition_route_group.TransitionRouteGroup(), + transition_route_group.TransitionRouteGroup(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_transition_route_groups(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_transition_route_group(transport: str = 'grpc', request_type=transition_route_group.GetTransitionRouteGroupRequest): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + ) + response = client.get_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_get_transition_route_group_from_dict(): + test_get_transition_route_group(request_type=dict) + + +def test_get_transition_route_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group), + '__call__') as call: + client.get_transition_route_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() + + +@pytest.mark.asyncio +async def test_get_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.GetTransitionRouteGroupRequest): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + )) + response = await client.get_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_transition_route_group_async_from_dict(): + await test_get_transition_route_group_async(request_type=dict) + + +def test_get_transition_route_group_field_headers(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.GetTransitionRouteGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transition_route_group), + '__call__') as call: + call.return_value = transition_route_group.TransitionRouteGroup() + client.get_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_transition_route_group_field_headers_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.GetTransitionRouteGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transition_route_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup()) + await client.get_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_transition_route_group_flattened(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.TransitionRouteGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_transition_route_group( + name='name_value', + ) + + # Establish that the 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_transition_route_group_flattened_error(): + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group( + transition_route_group.GetTransitionRouteGroupRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_transition_route_group_flattened_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = transition_route_group.TransitionRouteGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_transition_route_group( + 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_transition_route_group_flattened_error_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_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_transition_route_group( + transition_route_group.GetTransitionRouteGroupRequest(), + name='name_value', + ) + + +def test_create_transition_route_group(transport: str = 'grpc', request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + ) + response = client.create_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_create_transition_route_group_from_dict(): + test_create_transition_route_group(request_type=dict) + + +def test_create_transition_route_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group), + '__call__') as call: + client.create_transition_route_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + + +@pytest.mark.asyncio +async def test_create_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + )) + response = await client.create_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_create_transition_route_group_async_from_dict(): + await test_create_transition_route_group_async(request_type=dict) + + +def test_create_transition_route_group_field_headers(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transition_route_group), + '__call__') as call: + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + client.create_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_transition_route_group_field_headers_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transition_route_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) + await client.create_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_transition_route_group_flattened(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_transition_route_group( + parent='parent_value', + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') + + +def test_create_transition_route_group_flattened_error(): + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group( + gcdc_transition_route_group.CreateTransitionRouteGroupRequest(), + parent='parent_value', + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_transition_route_group_flattened_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_transition_route_group( + parent='parent_value', + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') + + +@pytest.mark.asyncio +async def test_create_transition_route_group_flattened_error_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_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_transition_route_group( + gcdc_transition_route_group.CreateTransitionRouteGroupRequest(), + parent='parent_value', + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), + ) + + +def test_update_transition_route_group(transport: str = 'grpc', request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + ) + response = client.update_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_transition_route_group_from_dict(): + test_update_transition_route_group(request_type=dict) + + +def test_update_transition_route_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group), + '__call__') as call: + client.update_transition_route_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + + +@pytest.mark.asyncio +async def test_update_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_transition_route_group_async_from_dict(): + await test_update_transition_route_group_async(request_type=dict) + + +def test_update_transition_route_group_field_headers(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + + request.transition_route_group.name = 'transition_route_group.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transition_route_group), + '__call__') as call: + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + client.update_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'transition_route_group.name=transition_route_group.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_transition_route_group_field_headers_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + + request.transition_route_group.name = 'transition_route_group.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transition_route_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) + await client.update_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'transition_route_group.name=transition_route_group.name/value', + ) in kw['metadata'] + + +def test_update_transition_route_group_flattened(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_transition_route_group( + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_transition_route_group_flattened_error(): + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group( + gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(), + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_transition_route_group_flattened_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_transition_route_group.TransitionRouteGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_transition_route_group( + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_transition_route_group_flattened_error_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_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_transition_route_group( + gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(), + transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_transition_route_group(transport: str = 'grpc', request_type=transition_route_group.DeleteTransitionRouteGroupRequest): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_transition_route_group_from_dict(): + test_delete_transition_route_group(request_type=dict) + + +def test_delete_transition_route_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group), + '__call__') as call: + client.delete_transition_route_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() + + +@pytest.mark.asyncio +async def test_delete_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.DeleteTransitionRouteGroupRequest): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_transition_route_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_transition_route_group_async_from_dict(): + await test_delete_transition_route_group_async(request_type=dict) + + +def test_delete_transition_route_group_field_headers(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.DeleteTransitionRouteGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transition_route_group), + '__call__') as call: + call.return_value = None + client.delete_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_transition_route_group_field_headers_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = transition_route_group.DeleteTransitionRouteGroupRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transition_route_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_transition_route_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_transition_route_group_flattened(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transition_route_group), + '__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_transition_route_group( + 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_transition_route_group_flattened_error(): + client = TransitionRouteGroupsClient( + credentials=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_transition_route_group( + transition_route_group.DeleteTransitionRouteGroupRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_transition_route_group_flattened_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_transition_route_group), + '__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_transition_route_group( + 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_transition_route_group_flattened_error_async(): + client = TransitionRouteGroupsAsyncClient( + credentials=ga_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_transition_route_group( + transition_route_group.DeleteTransitionRouteGroupRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TransitionRouteGroupsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TransitionRouteGroupsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TransitionRouteGroupsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TransitionRouteGroupsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TransitionRouteGroupsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TransitionRouteGroupsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TransitionRouteGroupsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TransitionRouteGroupsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TransitionRouteGroupsGrpcTransport, + transports.TransitionRouteGroupsGrpcAsyncIOTransport, +]) +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 = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TransitionRouteGroupsGrpcTransport, + ) + +def test_transition_route_groups_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TransitionRouteGroupsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_transition_route_groups_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TransitionRouteGroupsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_transition_route_groups', + 'get_transition_route_group', + 'create_transition_route_group', + 'update_transition_route_group', + 'delete_transition_route_group', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_transition_route_groups_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TransitionRouteGroupsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_transition_route_groups_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TransitionRouteGroupsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_transition_route_groups_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TransitionRouteGroupsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_transition_route_groups_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TransitionRouteGroupsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_transition_route_groups_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + TransitionRouteGroupsClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TransitionRouteGroupsGrpcTransport, + transports.TransitionRouteGroupsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_transition_route_groups_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TransitionRouteGroupsGrpcTransport, + transports.TransitionRouteGroupsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_transition_route_groups_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_transition_route_groups_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_transition_route_groups_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_transition_route_groups_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) +def test_transition_route_groups_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_transition_route_groups_host_no_port(): + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_transition_route_groups_host_with_port(): + client = TransitionRouteGroupsClient( + 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_transition_route_groups_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TransitionRouteGroupsGrpcTransport( + 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_transition_route_groups_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport( + 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.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) +def test_transition_route_groups_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.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) +def test_transition_route_groups_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_flow_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) + actual = TransitionRouteGroupsClient.flow_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "flow": "mussel", + } + path = TransitionRouteGroupsClient.flow_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_flow_path(path) + assert expected == actual + +def test_intent_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + intent = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) + actual = TransitionRouteGroupsClient.intent_path(project, location, agent, intent) + assert expected == actual + + +def test_parse_intent_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "intent": "octopus", + } + path = TransitionRouteGroupsClient.intent_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_intent_path(path) + assert expected == actual + +def test_page_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + flow = "mussel" + page = "winkle" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) + actual = TransitionRouteGroupsClient.page_path(project, location, agent, flow, page) + assert expected == actual + + +def test_parse_page_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "agent": "abalone", + "flow": "squid", + "page": "clam", + } + path = TransitionRouteGroupsClient.page_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_page_path(path) + assert expected == actual + +def test_transition_route_group_path(): + project = "whelk" + location = "octopus" + agent = "oyster" + flow = "nudibranch" + transition_route_group = "cuttlefish" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) + actual = TransitionRouteGroupsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) + assert expected == actual + + +def test_parse_transition_route_group_path(): + expected = { + "project": "mussel", + "location": "winkle", + "agent": "nautilus", + "flow": "scallop", + "transition_route_group": "abalone", + } + path = TransitionRouteGroupsClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_transition_route_group_path(path) + assert expected == actual + +def test_webhook_path(): + project = "squid" + location = "clam" + agent = "whelk" + webhook = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = TransitionRouteGroupsClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "agent": "cuttlefish", + "webhook": "mussel", + } + path = TransitionRouteGroupsClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TransitionRouteGroupsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = TransitionRouteGroupsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = TransitionRouteGroupsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = TransitionRouteGroupsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TransitionRouteGroupsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = TransitionRouteGroupsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = TransitionRouteGroupsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = TransitionRouteGroupsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.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 = TransitionRouteGroupsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = TransitionRouteGroupsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TransitionRouteGroupsClient.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.TransitionRouteGroupsTransport, '_prep_wrapped_messages') as prep: + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TransitionRouteGroupsTransport, '_prep_wrapped_messages') as prep: + transport_class = TransitionRouteGroupsClient.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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py new file mode 100644 index 00000000..a76f2996 --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py @@ -0,0 +1,2658 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.versions import VersionsAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.versions import VersionsClient +from google.cloud.dialogflowcx_v3beta1.services.versions import pagers +from google.cloud.dialogflowcx_v3beta1.services.versions import transports +from google.cloud.dialogflowcx_v3beta1.services.versions.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.versions.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import flow +from google.cloud.dialogflowcx_v3beta1.types import version +from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # 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(): + 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.dialogflowcx_v3beta1.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', + display_name='display_name_value', + description='description_value', + state=version.Version.State.RUNNING, + ) + response = client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == version.Version.State.RUNNING + + +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', + display_name='display_name_value', + description='description_value', + state=version.Version.State.RUNNING, + )) + response = await client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, version.Version) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == version.Version.State.RUNNING + + +@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=gcdc_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 = operations_pb2.Operation(name='operations/spam') + response = client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +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] == gcdc_version.CreateVersionRequest() + + +@pytest.mark.asyncio +async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@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 = gcdc_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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 = gcdc_version.CreateVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + 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 = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_version( + parent='parent_value', + version=gcdc_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 == gcdc_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( + gcdc_version.CreateVersionRequest(), + parent='parent_value', + version=gcdc_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 = 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_version( + parent='parent_value', + version=gcdc_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 == gcdc_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( + gcdc_version.CreateVersionRequest(), + parent='parent_value', + version=gcdc_version.Version(name='name_value'), + ) + + +def test_update_version(transport: str = 'grpc', request_type=gcdc_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 = gcdc_version.Version( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_version.Version.State.RUNNING, + ) + response = client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_version.Version) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_version.Version.State.RUNNING + + +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] == gcdc_version.UpdateVersionRequest() + + +@pytest.mark.asyncio +async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_version.Version( + name='name_value', + display_name='display_name_value', + description='description_value', + state=gcdc_version.Version.State.RUNNING, + )) + response = await client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_version.Version) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == gcdc_version.Version.State.RUNNING + + +@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 = gcdc_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = gcdc_version.Version() + client.update_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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 = gcdc_version.UpdateVersionRequest() + + request.version.name = 'version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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 = gcdc_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_version( + version=gcdc_version.Version(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].version == gcdc_version.Version(name='name_value') + assert args[0].update_mask == field_mask_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( + gcdc_version.UpdateVersionRequest(), + version=gcdc_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 = gcdc_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( + gcdc_version.UpdateVersionRequest(), + version=gcdc_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_load_version(transport: str = 'grpc', request_type=version.LoadVersionRequest): + 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.load_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.load_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == version.LoadVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_load_version_from_dict(): + test_load_version(request_type=dict) + + +def test_load_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_version), + '__call__') as call: + client.load_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.LoadVersionRequest() + + +@pytest.mark.asyncio +async def test_load_version_async(transport: str = 'grpc_asyncio', request_type=version.LoadVersionRequest): + 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.load_version), + '__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.load_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == version.LoadVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_load_version_async_from_dict(): + await test_load_version_async(request_type=dict) + + +def test_load_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.LoadVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_version), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.load_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_load_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.LoadVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.load_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_load_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.load_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.load_version( + name='name_value', + ) + + # Establish that the 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_load_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.load_version( + version.LoadVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_load_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.load_version), + '__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.load_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_load_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.load_version( + version.LoadVersionRequest(), + 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.dialogflowcx_v3beta1.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', + 'load_version', + ) + 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_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.dialogflowcx_v3beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_versions_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + 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.dialogflowcx_v3beta1.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_versions_grpc_lro_client(): + client = VersionsClient( + 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_versions_grpc_lro_async_client(): + client = VersionsAsyncClient( + 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_version_path(): + project = "squid" + location = "clam" + agent = "whelk" + flow = "octopus" + version = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) + actual = VersionsClient.version_path(project, location, agent, flow, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "flow": "winkle", + "version": "nautilus", + } + 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 = "scallop" + 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": "abalone", + } + 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 = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = VersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + 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 = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + 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 = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = VersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + 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 = "cuttlefish" + location = "mussel" + 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": "winkle", + "location": "nautilus", + } + 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py new file mode 100644 index 00000000..d4598d7c --- /dev/null +++ b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py @@ -0,0 +1,2409 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.webhooks import WebhooksAsyncClient +from google.cloud.dialogflowcx_v3beta1.services.webhooks import WebhooksClient +from google.cloud.dialogflowcx_v3beta1.services.webhooks import pagers +from google.cloud.dialogflowcx_v3beta1.services.webhooks import transports +from google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.base import _API_CORE_VERSION +from google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.dialogflowcx_v3beta1.types import webhook +from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # 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(): + 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 WebhooksClient._get_default_mtls_endpoint(None) is None + assert WebhooksClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert WebhooksClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert WebhooksClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert WebhooksClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert WebhooksClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + WebhooksClient, + WebhooksAsyncClient, +]) +def test_webhooks_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", [ + WebhooksClient, + WebhooksAsyncClient, +]) +def test_webhooks_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_webhooks_client_get_transport_class(): + transport = WebhooksClient.get_transport_class() + available_transports = [ + transports.WebhooksGrpcTransport, + ] + assert transport in available_transports + + transport = WebhooksClient.get_transport_class("grpc") + assert transport == transports.WebhooksGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), + (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(WebhooksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksClient)) +@mock.patch.object(WebhooksAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksAsyncClient)) +def test_webhooks_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(WebhooksClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=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(WebhooksClient, '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", [ + (WebhooksClient, transports.WebhooksGrpcTransport, "grpc", "true"), + (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (WebhooksClient, transports.WebhooksGrpcTransport, "grpc", "false"), + (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(WebhooksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksClient)) +@mock.patch.object(WebhooksAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_webhooks_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", [ + (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), + (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_webhooks_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", [ + (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), + (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_webhooks_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_webhooks_client_client_options_from_dict(): + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = WebhooksClient( + 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_webhooks(transport: str = 'grpc', request_type=webhook.ListWebhooksRequest): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhooks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.ListWebhooksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_webhooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.ListWebhooksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWebhooksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_webhooks_from_dict(): + test_list_webhooks(request_type=dict) + + +def test_list_webhooks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebhooksClient( + credentials=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_webhooks), + '__call__') as call: + client.list_webhooks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.ListWebhooksRequest() + + +@pytest.mark.asyncio +async def test_list_webhooks_async(transport: str = 'grpc_asyncio', request_type=webhook.ListWebhooksRequest): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhooks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_webhooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.ListWebhooksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWebhooksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_webhooks_async_from_dict(): + await test_list_webhooks_async(request_type=dict) + + +def test_list_webhooks_field_headers(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.ListWebhooksRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + call.return_value = webhook.ListWebhooksResponse() + client.list_webhooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_webhooks_field_headers_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.ListWebhooksRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse()) + await client.list_webhooks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_webhooks_flattened(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.ListWebhooksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_webhooks( + parent='parent_value', + ) + + # Establish that the 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_webhooks_flattened_error(): + client = WebhooksClient( + credentials=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_webhooks( + webhook.ListWebhooksRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_webhooks_flattened_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.ListWebhooksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_webhooks( + 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_webhooks_flattened_error_async(): + client = WebhooksAsyncClient( + credentials=ga_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_webhooks( + webhook.ListWebhooksRequest(), + parent='parent_value', + ) + + +def test_list_webhooks_pager(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + webhook.Webhook(), + ], + next_page_token='abc', + ), + webhook.ListWebhooksResponse( + webhooks=[], + next_page_token='def', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + ], + next_page_token='ghi', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_webhooks(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, webhook.Webhook) + for i in results) + +def test_list_webhooks_pages(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + webhook.Webhook(), + ], + next_page_token='abc', + ), + webhook.ListWebhooksResponse( + webhooks=[], + next_page_token='def', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + ], + next_page_token='ghi', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + ], + ), + RuntimeError, + ) + pages = list(client.list_webhooks(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_webhooks_async_pager(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + webhook.Webhook(), + ], + next_page_token='abc', + ), + webhook.ListWebhooksResponse( + webhooks=[], + next_page_token='def', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + ], + next_page_token='ghi', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_webhooks(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, webhook.Webhook) + for i in responses) + +@pytest.mark.asyncio +async def test_list_webhooks_async_pages(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_webhooks), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + webhook.Webhook(), + ], + next_page_token='abc', + ), + webhook.ListWebhooksResponse( + webhooks=[], + next_page_token='def', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + ], + next_page_token='ghi', + ), + webhook.ListWebhooksResponse( + webhooks=[ + webhook.Webhook(), + webhook.Webhook(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_webhooks(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_webhook(transport: str = 'grpc', request_type=webhook.GetWebhookRequest): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + generic_web_service=webhook.Webhook.GenericWebService(uri='uri_value'), + ) + response = client.get_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.GetWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +def test_get_webhook_from_dict(): + test_get_webhook(request_type=dict) + + +def test_get_webhook_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebhooksClient( + credentials=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_webhook), + '__call__') as call: + client.get_webhook() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.GetWebhookRequest() + + +@pytest.mark.asyncio +async def test_get_webhook_async(transport: str = 'grpc_asyncio', request_type=webhook.GetWebhookRequest): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + )) + response = await client.get_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.GetWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_get_webhook_async_from_dict(): + await test_get_webhook_async(request_type=dict) + + +def test_get_webhook_field_headers(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.GetWebhookRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_webhook), + '__call__') as call: + call.return_value = webhook.Webhook() + client.get_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_webhook_field_headers_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.GetWebhookRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_webhook), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook()) + await client.get_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_webhook_flattened(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.Webhook() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_webhook( + name='name_value', + ) + + # Establish that the 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_webhook_flattened_error(): + client = WebhooksClient( + credentials=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_webhook( + webhook.GetWebhookRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_webhook_flattened_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = webhook.Webhook() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_webhook( + 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_webhook_flattened_error_async(): + client = WebhooksAsyncClient( + credentials=ga_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_webhook( + webhook.GetWebhookRequest(), + name='name_value', + ) + + +def test_create_webhook(transport: str = 'grpc', request_type=gcdc_webhook.CreateWebhookRequest): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri='uri_value'), + ) + response = client.create_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.CreateWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +def test_create_webhook_from_dict(): + test_create_webhook(request_type=dict) + + +def test_create_webhook_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebhooksClient( + credentials=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_webhook), + '__call__') as call: + client.create_webhook() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.CreateWebhookRequest() + + +@pytest.mark.asyncio +async def test_create_webhook_async(transport: str = 'grpc_asyncio', request_type=gcdc_webhook.CreateWebhookRequest): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + )) + response = await client.create_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.CreateWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_create_webhook_async_from_dict(): + await test_create_webhook_async(request_type=dict) + + +def test_create_webhook_field_headers(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_webhook.CreateWebhookRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_webhook), + '__call__') as call: + call.return_value = gcdc_webhook.Webhook() + client.create_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_webhook_field_headers_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_webhook.CreateWebhookRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_webhook), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) + await client.create_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_webhook_flattened(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_webhook( + parent='parent_value', + webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') + + +def test_create_webhook_flattened_error(): + client = WebhooksClient( + credentials=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_webhook( + gcdc_webhook.CreateWebhookRequest(), + parent='parent_value', + webhook=gcdc_webhook.Webhook(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_webhook_flattened_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_webhook( + parent='parent_value', + webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') + + +@pytest.mark.asyncio +async def test_create_webhook_flattened_error_async(): + client = WebhooksAsyncClient( + credentials=ga_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_webhook( + gcdc_webhook.CreateWebhookRequest(), + parent='parent_value', + webhook=gcdc_webhook.Webhook(name='name_value'), + ) + + +def test_update_webhook(transport: str = 'grpc', request_type=gcdc_webhook.UpdateWebhookRequest): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri='uri_value'), + ) + response = client.update_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.UpdateWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +def test_update_webhook_from_dict(): + test_update_webhook(request_type=dict) + + +def test_update_webhook_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebhooksClient( + credentials=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_webhook), + '__call__') as call: + client.update_webhook() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.UpdateWebhookRequest() + + +@pytest.mark.asyncio +async def test_update_webhook_async(transport: str = 'grpc_asyncio', request_type=gcdc_webhook.UpdateWebhookRequest): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook( + name='name_value', + display_name='display_name_value', + disabled=True, + )) + response = await client.update_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcdc_webhook.UpdateWebhookRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcdc_webhook.Webhook) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_update_webhook_async_from_dict(): + await test_update_webhook_async(request_type=dict) + + +def test_update_webhook_field_headers(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_webhook.UpdateWebhookRequest() + + request.webhook.name = 'webhook.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_webhook), + '__call__') as call: + call.return_value = gcdc_webhook.Webhook() + client.update_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'webhook.name=webhook.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_webhook_field_headers_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcdc_webhook.UpdateWebhookRequest() + + request.webhook.name = 'webhook.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_webhook), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) + await client.update_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'webhook.name=webhook.name/value', + ) in kw['metadata'] + + +def test_update_webhook_flattened(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_webhook( + webhook=gcdc_webhook.Webhook(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].webhook == gcdc_webhook.Webhook(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_webhook_flattened_error(): + client = WebhooksClient( + credentials=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_webhook( + gcdc_webhook.UpdateWebhookRequest(), + webhook=gcdc_webhook.Webhook(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_webhook_flattened_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcdc_webhook.Webhook() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_webhook( + webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_webhook_flattened_error_async(): + client = WebhooksAsyncClient( + credentials=ga_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_webhook( + gcdc_webhook.UpdateWebhookRequest(), + webhook=gcdc_webhook.Webhook(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_webhook(transport: str = 'grpc', request_type=webhook.DeleteWebhookRequest): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.DeleteWebhookRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_webhook_from_dict(): + test_delete_webhook(request_type=dict) + + +def test_delete_webhook_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = WebhooksClient( + credentials=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_webhook), + '__call__') as call: + client.delete_webhook() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.DeleteWebhookRequest() + + +@pytest.mark.asyncio +async def test_delete_webhook_async(transport: str = 'grpc_asyncio', request_type=webhook.DeleteWebhookRequest): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == webhook.DeleteWebhookRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_webhook_async_from_dict(): + await test_delete_webhook_async(request_type=dict) + + +def test_delete_webhook_field_headers(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.DeleteWebhookRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_webhook), + '__call__') as call: + call.return_value = None + client.delete_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_webhook_field_headers_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = webhook.DeleteWebhookRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_webhook), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_webhook(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_webhook_flattened(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_webhook), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_webhook( + name='name_value', + ) + + # Establish that the 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_webhook_flattened_error(): + client = WebhooksClient( + credentials=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_webhook( + webhook.DeleteWebhookRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_webhook_flattened_async(): + client = WebhooksAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_webhook), + '__call__') as call: + # 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_webhook( + 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_webhook_flattened_error_async(): + client = WebhooksAsyncClient( + credentials=ga_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_webhook( + webhook.DeleteWebhookRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebhooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebhooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebhooksClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebhooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebhooksClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebhooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebhooksClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebhooksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebhooksGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.WebhooksGrpcTransport, + transports.WebhooksGrpcAsyncIOTransport, +]) +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 = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebhooksGrpcTransport, + ) + +def test_webhooks_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebhooksTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_webhooks_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.WebhooksTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_webhooks', + 'get_webhook', + 'create_webhook', + 'update_webhook', + 'delete_webhook', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_webhooks_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebhooksTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_webhooks_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebhooksTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', + ), + quota_project_id="octopus", + ) + + +def test_webhooks_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebhooksTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_webhooks_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WebhooksClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_webhooks_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WebhooksClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebhooksGrpcTransport, + transports.WebhooksGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_webhooks_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebhooksGrpcTransport, + transports.WebhooksGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_webhooks_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_gte_1_26_0 +def test_webhooks_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_webhooks_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/dialogflow', +), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +@requires_api_core_lt_1_26_0 +def test_webhooks_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) +def test_webhooks_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = 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_webhooks_host_no_port(): + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), + ) + assert client.transport._host == 'dialogflow.googleapis.com:443' + + +def test_webhooks_host_with_port(): + client = WebhooksClient( + 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_webhooks_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebhooksGrpcTransport( + 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_webhooks_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WebhooksGrpcAsyncIOTransport( + 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.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) +def test_webhooks_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.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) +def test_webhooks_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_service_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + actual = WebhooksClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "namespace": "cuttlefish", + "service": "mussel", + } + path = WebhooksClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_service_path(path) + assert expected == actual + +def test_webhook_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" + expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) + actual = WebhooksClient.webhook_path(project, location, agent, webhook) + assert expected == actual + + +def test_parse_webhook_path(): + expected = { + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", + } + path = WebhooksClient.webhook_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_webhook_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = WebhooksClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = WebhooksClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = WebhooksClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = WebhooksClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = WebhooksClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = WebhooksClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = WebhooksClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = WebhooksClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.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 = WebhooksClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = WebhooksClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WebhooksClient.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.WebhooksTransport, '_prep_wrapped_messages') as prep: + client = WebhooksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.WebhooksTransport, '_prep_wrapped_messages') as prep: + transport_class = WebhooksClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) From 431e95a6a5052c9b16b3ef977a635621dc552022 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 21 May 2021 02:49:43 +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 --- google/cloud/dialogflowcx_v3beta1/__init__.py | 12 + .../dialogflowcx_v3beta1/gapic_metadata.json | 20 + .../services/environments/async_client.py | 155 + .../services/environments/client.py | 196 + .../services/environments/pagers.py | 130 + .../services/environments/transports/base.py | 29 + .../services/environments/transports/grpc.py | 57 + .../environments/transports/grpc_asyncio.py | 59 + .../dialogflowcx_v3beta1/types/__init__.py | 12 + .../dialogflowcx_v3beta1/types/environment.py | 122 + owl-bot-staging/v3/MANIFEST.in | 2 - owl-bot-staging/v3/README.rst | 49 - owl-bot-staging/v3/docs/conf.py | 376 -- .../v3/docs/dialogflowcx_v3/agents.rst | 10 - .../v3/docs/dialogflowcx_v3/entity_types.rst | 10 - .../v3/docs/dialogflowcx_v3/environments.rst | 10 - .../v3/docs/dialogflowcx_v3/experiments.rst | 10 - .../v3/docs/dialogflowcx_v3/flows.rst | 10 - .../v3/docs/dialogflowcx_v3/intents.rst | 10 - .../v3/docs/dialogflowcx_v3/pages.rst | 10 - .../security_settings_service.rst | 10 - .../v3/docs/dialogflowcx_v3/services.rst | 19 - .../dialogflowcx_v3/session_entity_types.rst | 10 - .../v3/docs/dialogflowcx_v3/sessions.rst | 6 - .../v3/docs/dialogflowcx_v3/test_cases.rst | 10 - .../transition_route_groups.rst | 10 - .../v3/docs/dialogflowcx_v3/types.rst | 7 - .../v3/docs/dialogflowcx_v3/versions.rst | 10 - .../v3/docs/dialogflowcx_v3/webhooks.rst | 10 - owl-bot-staging/v3/docs/index.rst | 7 - .../v3/google/cloud/dialogflowcx/__init__.py | 439 -- .../v3/google/cloud/dialogflowcx/py.typed | 2 - .../google/cloud/dialogflowcx_v3/__init__.py | 440 -- .../cloud/dialogflowcx_v3/gapic_metadata.json | 1095 ----- .../v3/google/cloud/dialogflowcx_v3/py.typed | 2 - .../dialogflowcx_v3/services/__init__.py | 15 - .../services/agents/__init__.py | 22 - .../services/agents/async_client.py | 892 ---- .../dialogflowcx_v3/services/agents/client.py | 1127 ----- .../dialogflowcx_v3/services/agents/pagers.py | 140 - .../services/agents/transports/__init__.py | 33 - .../services/agents/transports/base.py | 304 -- .../services/agents/transports/grpc.py | 485 -- .../agents/transports/grpc_asyncio.py | 489 -- .../services/entity_types/__init__.py | 22 - .../services/entity_types/async_client.py | 659 --- .../services/entity_types/client.py | 846 ---- .../services/entity_types/pagers.py | 140 - .../entity_types/transports/__init__.py | 33 - .../services/entity_types/transports/base.py | 241 - .../services/entity_types/transports/grpc.py | 356 -- .../entity_types/transports/grpc_asyncio.py | 360 -- .../services/environments/__init__.py | 22 - .../services/environments/async_client.py | 723 --- .../services/environments/client.py | 919 ---- .../services/environments/pagers.py | 262 -- .../environments/transports/__init__.py | 33 - .../services/environments/transports/base.py | 262 -- .../services/environments/transports/grpc.py | 407 -- .../environments/transports/grpc_asyncio.py | 411 -- .../services/experiments/__init__.py | 22 - .../services/experiments/async_client.py | 738 --- .../services/experiments/client.py | 934 ---- .../services/experiments/pagers.py | 140 - .../experiments/transports/__init__.py | 33 - .../services/experiments/transports/base.py | 269 -- .../services/experiments/transports/grpc.py | 418 -- .../experiments/transports/grpc_asyncio.py | 422 -- .../services/flows/__init__.py | 22 - .../services/flows/async_client.py | 1008 ---- .../dialogflowcx_v3/services/flows/client.py | 1243 ----- .../dialogflowcx_v3/services/flows/pagers.py | 140 - .../services/flows/transports/__init__.py | 33 - .../services/flows/transports/base.py | 318 -- .../services/flows/transports/grpc.py | 511 --- .../services/flows/transports/grpc_asyncio.py | 515 --- .../services/intents/__init__.py | 22 - .../services/intents/async_client.py | 580 --- .../services/intents/client.py | 776 ---- .../services/intents/pagers.py | 140 - .../services/intents/transports/__init__.py | 33 - .../services/intents/transports/base.py | 241 - .../services/intents/transports/grpc.py | 356 -- .../intents/transports/grpc_asyncio.py | 360 -- .../services/pages/__init__.py | 22 - .../services/pages/async_client.py | 631 --- .../dialogflowcx_v3/services/pages/client.py | 863 ---- .../dialogflowcx_v3/services/pages/pagers.py | 140 - .../services/pages/transports/__init__.py | 33 - .../services/pages/transports/base.py | 241 - .../services/pages/transports/grpc.py | 354 -- .../services/pages/transports/grpc_asyncio.py | 358 -- .../security_settings_service/__init__.py | 22 - .../security_settings_service/async_client.py | 586 --- .../security_settings_service/client.py | 773 ---- .../security_settings_service/pagers.py | 140 - .../transports/__init__.py | 33 - .../transports/base.py | 241 - .../transports/grpc.py | 359 -- .../transports/grpc_asyncio.py | 363 -- .../services/session_entity_types/__init__.py | 22 - .../session_entity_types/async_client.py | 632 --- .../services/session_entity_types/client.py | 819 ---- .../services/session_entity_types/pagers.py | 140 - .../transports/__init__.py | 33 - .../session_entity_types/transports/base.py | 241 - .../session_entity_types/transports/grpc.py | 356 -- .../transports/grpc_asyncio.py | 360 -- .../services/sessions/__init__.py | 22 - .../services/sessions/async_client.py | 460 -- .../services/sessions/client.py | 703 --- .../services/sessions/transports/__init__.py | 33 - .../services/sessions/transports/base.py | 231 - .../services/sessions/transports/grpc.py | 350 -- .../sessions/transports/grpc_asyncio.py | 354 -- .../services/test_cases/__init__.py | 22 - .../services/test_cases/async_client.py | 1073 ----- .../services/test_cases/client.py | 1346 ------ .../services/test_cases/pagers.py | 262 -- .../test_cases/transports/__init__.py | 33 - .../services/test_cases/transports/base.py | 346 -- .../services/test_cases/transports/grpc.py | 562 --- .../test_cases/transports/grpc_asyncio.py | 566 --- .../transition_route_groups/__init__.py | 22 - .../transition_route_groups/async_client.py | 593 --- .../transition_route_groups/client.py | 816 ---- .../transition_route_groups/pagers.py | 140 - .../transports/__init__.py | 33 - .../transports/base.py | 241 - .../transports/grpc.py | 361 -- .../transports/grpc_asyncio.py | 365 -- .../services/versions/__init__.py | 22 - .../services/versions/async_client.py | 687 --- .../services/versions/client.py | 874 ---- .../services/versions/pagers.py | 140 - .../services/versions/transports/__init__.py | 33 - .../services/versions/transports/base.py | 262 -- .../services/versions/transports/grpc.py | 406 -- .../versions/transports/grpc_asyncio.py | 410 -- .../services/webhooks/__init__.py | 22 - .../services/webhooks/async_client.py | 581 --- .../services/webhooks/client.py | 777 ---- .../services/webhooks/pagers.py | 140 - .../services/webhooks/transports/__init__.py | 33 - .../services/webhooks/transports/base.py | 241 - .../services/webhooks/transports/grpc.py | 356 -- .../webhooks/transports/grpc_asyncio.py | 360 -- .../cloud/dialogflowcx_v3/types/__init__.py | 418 -- .../cloud/dialogflowcx_v3/types/agent.py | 491 -- .../dialogflowcx_v3/types/audio_config.py | 356 -- .../dialogflowcx_v3/types/entity_type.py | 425 -- .../dialogflowcx_v3/types/environment.py | 318 -- .../cloud/dialogflowcx_v3/types/experiment.py | 568 --- .../cloud/dialogflowcx_v3/types/flow.py | 640 --- .../dialogflowcx_v3/types/fulfillment.py | 182 - .../cloud/dialogflowcx_v3/types/intent.py | 474 -- .../cloud/dialogflowcx_v3/types/page.py | 730 --- .../dialogflowcx_v3/types/response_message.py | 340 -- .../types/security_settings.py | 267 -- .../cloud/dialogflowcx_v3/types/session.py | 1167 ----- .../types/session_entity_type.py | 254 -- .../cloud/dialogflowcx_v3/types/test_case.py | 1248 ----- .../types/transition_route_group.py | 307 -- .../types/validation_message.py | 113 - .../cloud/dialogflowcx_v3/types/version.py | 292 -- .../cloud/dialogflowcx_v3/types/webhook.py | 791 ---- owl-bot-staging/v3/mypy.ini | 3 - owl-bot-staging/v3/noxfile.py | 132 - .../scripts/fixup_dialogflowcx_v3_keywords.py | 264 -- owl-bot-staging/v3/setup.py | 53 - owl-bot-staging/v3/tests/__init__.py | 16 - owl-bot-staging/v3/tests/unit/__init__.py | 16 - .../v3/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/dialogflowcx_v3/__init__.py | 16 - .../unit/gapic/dialogflowcx_v3/test_agents.py | 3312 -------------- .../dialogflowcx_v3/test_entity_types.py | 2418 ---------- .../dialogflowcx_v3/test_environments.py | 2851 ------------ .../gapic/dialogflowcx_v3/test_experiments.py | 2911 ------------ .../unit/gapic/dialogflowcx_v3/test_flows.py | 3472 -------------- .../gapic/dialogflowcx_v3/test_intents.py | 2429 ---------- .../unit/gapic/dialogflowcx_v3/test_pages.py | 2504 ---------- .../test_security_settings_service.py | 2419 ---------- .../test_session_entity_types.py | 2373 ---------- .../gapic/dialogflowcx_v3/test_sessions.py | 1708 ------- .../gapic/dialogflowcx_v3/test_test_cases.py | 4061 ----------------- .../test_transition_route_groups.py | 2470 ---------- .../gapic/dialogflowcx_v3/test_versions.py | 2658 ----------- .../gapic/dialogflowcx_v3/test_webhooks.py | 2409 ---------- owl-bot-staging/v3beta1/MANIFEST.in | 2 - owl-bot-staging/v3beta1/README.rst | 49 - owl-bot-staging/v3beta1/docs/conf.py | 376 -- .../docs/dialogflowcx_v3beta1/agents.rst | 10 - .../dialogflowcx_v3beta1/entity_types.rst | 10 - .../dialogflowcx_v3beta1/environments.rst | 10 - .../docs/dialogflowcx_v3beta1/experiments.rst | 10 - .../docs/dialogflowcx_v3beta1/flows.rst | 10 - .../docs/dialogflowcx_v3beta1/intents.rst | 10 - .../docs/dialogflowcx_v3beta1/pages.rst | 10 - .../security_settings_service.rst | 10 - .../docs/dialogflowcx_v3beta1/services.rst | 19 - .../session_entity_types.rst | 10 - .../docs/dialogflowcx_v3beta1/sessions.rst | 6 - .../docs/dialogflowcx_v3beta1/test_cases.rst | 10 - .../transition_route_groups.rst | 10 - .../docs/dialogflowcx_v3beta1/types.rst | 7 - .../docs/dialogflowcx_v3beta1/versions.rst | 10 - .../docs/dialogflowcx_v3beta1/webhooks.rst | 10 - owl-bot-staging/v3beta1/docs/index.rst | 7 - .../google/cloud/dialogflowcx/__init__.py | 451 -- .../google/cloud/dialogflowcx/py.typed | 2 - .../cloud/dialogflowcx_v3beta1/__init__.py | 452 -- .../dialogflowcx_v3beta1/gapic_metadata.json | 1115 ----- .../cloud/dialogflowcx_v3beta1/py.typed | 2 - .../dialogflowcx_v3beta1/services/__init__.py | 15 - .../services/agents/__init__.py | 22 - .../services/agents/async_client.py | 894 ---- .../services/agents/client.py | 1129 ----- .../services/agents/pagers.py | 140 - .../services/agents/transports/__init__.py | 33 - .../services/agents/transports/base.py | 304 -- .../services/agents/transports/grpc.py | 486 -- .../agents/transports/grpc_asyncio.py | 490 -- .../services/entity_types/__init__.py | 22 - .../services/entity_types/async_client.py | 659 --- .../services/entity_types/client.py | 846 ---- .../services/entity_types/pagers.py | 140 - .../entity_types/transports/__init__.py | 33 - .../services/entity_types/transports/base.py | 241 - .../services/entity_types/transports/grpc.py | 356 -- .../entity_types/transports/grpc_asyncio.py | 360 -- .../services/environments/__init__.py | 22 - .../services/environments/async_client.py | 883 ---- .../services/environments/client.py | 1098 ----- .../services/environments/pagers.py | 384 -- .../environments/transports/__init__.py | 33 - .../services/environments/transports/base.py | 290 -- .../services/environments/transports/grpc.py | 461 -- .../environments/transports/grpc_asyncio.py | 465 -- .../services/experiments/__init__.py | 22 - .../services/experiments/async_client.py | 740 --- .../services/experiments/client.py | 936 ---- .../services/experiments/pagers.py | 140 - .../experiments/transports/__init__.py | 33 - .../services/experiments/transports/base.py | 269 -- .../services/experiments/transports/grpc.py | 420 -- .../experiments/transports/grpc_asyncio.py | 424 -- .../services/flows/__init__.py | 22 - .../services/flows/async_client.py | 1010 ---- .../services/flows/client.py | 1245 ----- .../services/flows/pagers.py | 140 - .../services/flows/transports/__init__.py | 33 - .../services/flows/transports/base.py | 318 -- .../services/flows/transports/grpc.py | 512 --- .../services/flows/transports/grpc_asyncio.py | 516 --- .../services/intents/__init__.py | 22 - .../services/intents/async_client.py | 580 --- .../services/intents/client.py | 776 ---- .../services/intents/pagers.py | 140 - .../services/intents/transports/__init__.py | 33 - .../services/intents/transports/base.py | 241 - .../services/intents/transports/grpc.py | 356 -- .../intents/transports/grpc_asyncio.py | 360 -- .../services/pages/__init__.py | 22 - .../services/pages/async_client.py | 633 --- .../services/pages/client.py | 865 ---- .../services/pages/pagers.py | 140 - .../services/pages/transports/__init__.py | 33 - .../services/pages/transports/base.py | 241 - .../services/pages/transports/grpc.py | 355 -- .../services/pages/transports/grpc_asyncio.py | 359 -- .../security_settings_service/__init__.py | 22 - .../security_settings_service/async_client.py | 586 --- .../security_settings_service/client.py | 773 ---- .../security_settings_service/pagers.py | 140 - .../transports/__init__.py | 33 - .../transports/base.py | 241 - .../transports/grpc.py | 359 -- .../transports/grpc_asyncio.py | 363 -- .../services/session_entity_types/__init__.py | 22 - .../session_entity_types/async_client.py | 635 --- .../services/session_entity_types/client.py | 822 ---- .../services/session_entity_types/pagers.py | 140 - .../transports/__init__.py | 33 - .../session_entity_types/transports/base.py | 241 - .../session_entity_types/transports/grpc.py | 356 -- .../transports/grpc_asyncio.py | 360 -- .../services/sessions/__init__.py | 22 - .../services/sessions/async_client.py | 460 -- .../services/sessions/client.py | 703 --- .../services/sessions/transports/__init__.py | 33 - .../services/sessions/transports/base.py | 231 - .../services/sessions/transports/grpc.py | 350 -- .../sessions/transports/grpc_asyncio.py | 354 -- .../services/test_cases/__init__.py | 22 - .../services/test_cases/async_client.py | 1073 ----- .../services/test_cases/client.py | 1346 ------ .../services/test_cases/pagers.py | 262 -- .../test_cases/transports/__init__.py | 33 - .../services/test_cases/transports/base.py | 346 -- .../services/test_cases/transports/grpc.py | 562 --- .../test_cases/transports/grpc_asyncio.py | 566 --- .../transition_route_groups/__init__.py | 22 - .../transition_route_groups/async_client.py | 593 --- .../transition_route_groups/client.py | 816 ---- .../transition_route_groups/pagers.py | 140 - .../transports/__init__.py | 33 - .../transports/base.py | 241 - .../transports/grpc.py | 361 -- .../transports/grpc_asyncio.py | 365 -- .../services/versions/__init__.py | 22 - .../services/versions/async_client.py | 690 --- .../services/versions/client.py | 877 ---- .../services/versions/pagers.py | 140 - .../services/versions/transports/__init__.py | 33 - .../services/versions/transports/base.py | 262 -- .../services/versions/transports/grpc.py | 407 -- .../versions/transports/grpc_asyncio.py | 411 -- .../services/webhooks/__init__.py | 22 - .../services/webhooks/async_client.py | 581 --- .../services/webhooks/client.py | 777 ---- .../services/webhooks/pagers.py | 140 - .../services/webhooks/transports/__init__.py | 33 - .../services/webhooks/transports/base.py | 241 - .../services/webhooks/transports/grpc.py | 356 -- .../webhooks/transports/grpc_asyncio.py | 360 -- .../dialogflowcx_v3beta1/types/__init__.py | 430 -- .../cloud/dialogflowcx_v3beta1/types/agent.py | 491 -- .../types/audio_config.py | 357 -- .../dialogflowcx_v3beta1/types/entity_type.py | 425 -- .../dialogflowcx_v3beta1/types/environment.py | 478 -- .../dialogflowcx_v3beta1/types/experiment.py | 570 --- .../cloud/dialogflowcx_v3beta1/types/flow.py | 640 --- .../dialogflowcx_v3beta1/types/fulfillment.py | 182 - .../dialogflowcx_v3beta1/types/intent.py | 474 -- .../cloud/dialogflowcx_v3beta1/types/page.py | 730 --- .../types/response_message.py | 340 -- .../types/security_settings.py | 267 -- .../dialogflowcx_v3beta1/types/session.py | 1172 ----- .../types/session_entity_type.py | 254 -- .../dialogflowcx_v3beta1/types/test_case.py | 1250 ----- .../types/transition_route_group.py | 307 -- .../types/validation_message.py | 113 - .../dialogflowcx_v3beta1/types/version.py | 295 -- .../dialogflowcx_v3beta1/types/webhook.py | 793 ---- owl-bot-staging/v3beta1/mypy.ini | 3 - owl-bot-staging/v3beta1/noxfile.py | 132 - .../fixup_dialogflowcx_v3beta1_keywords.py | 266 -- owl-bot-staging/v3beta1/setup.py | 53 - owl-bot-staging/v3beta1/tests/__init__.py | 16 - .../v3beta1/tests/unit/__init__.py | 16 - .../v3beta1/tests/unit/gapic/__init__.py | 16 - .../gapic/dialogflowcx_v3beta1/__init__.py | 16 - .../gapic/dialogflowcx_v3beta1/test_agents.py | 3312 -------------- .../dialogflowcx_v3beta1/test_entity_types.py | 2418 ---------- .../dialogflowcx_v3beta1/test_environments.py | 3467 -------------- .../dialogflowcx_v3beta1/test_experiments.py | 2911 ------------ .../gapic/dialogflowcx_v3beta1/test_flows.py | 3472 -------------- .../dialogflowcx_v3beta1/test_intents.py | 2429 ---------- .../gapic/dialogflowcx_v3beta1/test_pages.py | 2504 ---------- .../test_security_settings_service.py | 2419 ---------- .../test_session_entity_types.py | 2373 ---------- .../dialogflowcx_v3beta1/test_sessions.py | 1708 ------- .../dialogflowcx_v3beta1/test_test_cases.py | 4061 ----------------- .../test_transition_route_groups.py | 2470 ---------- .../dialogflowcx_v3beta1/test_versions.py | 2658 ----------- .../dialogflowcx_v3beta1/test_webhooks.py | 2409 ---------- .../dialogflowcx_v3beta1/test_environments.py | 651 ++- 367 files changed, 1416 insertions(+), 183479 deletions(-) delete mode 100644 owl-bot-staging/v3/MANIFEST.in delete mode 100644 owl-bot-staging/v3/README.rst delete mode 100644 owl-bot-staging/v3/docs/conf.py delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/agents.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst delete mode 100644 owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst delete mode 100644 owl-bot-staging/v3/docs/index.rst delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session_entity_type.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/test_case.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/transition_route_group.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/validation_message.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/version.py delete mode 100644 owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/webhook.py delete mode 100644 owl-bot-staging/v3/mypy.ini delete mode 100644 owl-bot-staging/v3/noxfile.py delete mode 100644 owl-bot-staging/v3/scripts/fixup_dialogflowcx_v3_keywords.py delete mode 100644 owl-bot-staging/v3/setup.py delete mode 100644 owl-bot-staging/v3/tests/__init__.py delete mode 100644 owl-bot-staging/v3/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/__init__.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_agents.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_environments.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_experiments.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_flows.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_intents.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_pages.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_sessions.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_versions.py delete mode 100644 owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py delete mode 100644 owl-bot-staging/v3beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v3beta1/README.rst delete mode 100644 owl-bot-staging/v3beta1/docs/conf.py delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/agents.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/entity_types.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/environments.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/experiments.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/flows.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/intents.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/pages.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/security_settings_service.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/services.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/session_entity_types.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/sessions.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/test_cases.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/transition_route_groups.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/types.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/versions.rst delete mode 100644 owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/webhooks.rst delete mode 100644 owl-bot-staging/v3beta1/docs/index.rst delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx/py.typed delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/py.typed delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/__init__.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/agent.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/audio_config.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/entity_type.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/environment.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/experiment.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/flow.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/intent.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/page.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/response_message.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/security_settings.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/test_case.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/validation_message.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/version.py delete mode 100644 owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/webhook.py delete mode 100644 owl-bot-staging/v3beta1/mypy.ini delete mode 100644 owl-bot-staging/v3beta1/noxfile.py delete mode 100644 owl-bot-staging/v3beta1/scripts/fixup_dialogflowcx_v3beta1_keywords.py delete mode 100644 owl-bot-staging/v3beta1/setup.py delete mode 100644 owl-bot-staging/v3beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py delete mode 100644 owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py diff --git a/google/cloud/dialogflowcx_v3beta1/__init__.py b/google/cloud/dialogflowcx_v3beta1/__init__.py index db4a67fb..b89fa426 100644 --- a/google/cloud/dialogflowcx_v3beta1/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/__init__.py @@ -73,14 +73,20 @@ from .types.entity_type import ListEntityTypesRequest from .types.entity_type import ListEntityTypesResponse from .types.entity_type import UpdateEntityTypeRequest +from .types.environment import ContinuousTestResult from .types.environment import CreateEnvironmentRequest from .types.environment import DeleteEnvironmentRequest from .types.environment import Environment from .types.environment import GetEnvironmentRequest +from .types.environment import ListContinuousTestResultsRequest +from .types.environment import ListContinuousTestResultsResponse from .types.environment import ListEnvironmentsRequest from .types.environment import ListEnvironmentsResponse from .types.environment import LookupEnvironmentHistoryRequest from .types.environment import LookupEnvironmentHistoryResponse +from .types.environment import RunContinuousTestMetadata +from .types.environment import RunContinuousTestRequest +from .types.environment import RunContinuousTestResponse from .types.environment import UpdateEnvironmentRequest from .types.experiment import CreateExperimentRequest from .types.experiment import DeleteExperimentRequest @@ -252,6 +258,7 @@ "BatchRunTestCasesResponse", "CalculateCoverageRequest", "CalculateCoverageResponse", + "ContinuousTestResult", "ConversationTurn", "CreateAgentRequest", "CreateEntityTypeRequest", @@ -333,6 +340,8 @@ "IntentsClient", "ListAgentsRequest", "ListAgentsResponse", + "ListContinuousTestResultsRequest", + "ListContinuousTestResultsResponse", "ListEntityTypesRequest", "ListEntityTypesResponse", "ListEnvironmentsRequest", @@ -377,6 +386,9 @@ "ResourceName", "ResponseMessage", "RestoreAgentRequest", + "RunContinuousTestMetadata", + "RunContinuousTestRequest", + "RunContinuousTestResponse", "RunTestCaseMetadata", "RunTestCaseRequest", "RunTestCaseResponse", diff --git a/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json b/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json index c8dd46f2..661610d7 100644 --- a/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json +++ b/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json @@ -193,6 +193,11 @@ "get_environment" ] }, + "ListContinuousTestResults": { + "methods": [ + "list_continuous_test_results" + ] + }, "ListEnvironments": { "methods": [ "list_environments" @@ -203,6 +208,11 @@ "lookup_environment_history" ] }, + "RunContinuousTest": { + "methods": [ + "run_continuous_test" + ] + }, "UpdateEnvironment": { "methods": [ "update_environment" @@ -228,6 +238,11 @@ "get_environment" ] }, + "ListContinuousTestResults": { + "methods": [ + "list_continuous_test_results" + ] + }, "ListEnvironments": { "methods": [ "list_environments" @@ -238,6 +253,11 @@ "lookup_environment_history" ] }, + "RunContinuousTest": { + "methods": [ + "run_continuous_test" + ] + }, "UpdateEnvironment": { "methods": [ "update_environment" diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py index 7f9c961c..dc94b16b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py @@ -49,8 +49,18 @@ class EnvironmentsAsyncClient: DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + continuous_test_result_path = staticmethod( + EnvironmentsClient.continuous_test_result_path + ) + parse_continuous_test_result_path = staticmethod( + EnvironmentsClient.parse_continuous_test_result_path + ) environment_path = staticmethod(EnvironmentsClient.environment_path) parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) + test_case_result_path = staticmethod(EnvironmentsClient.test_case_result_path) + parse_test_case_result_path = staticmethod( + EnvironmentsClient.parse_test_case_result_path + ) version_path = staticmethod(EnvironmentsClient.version_path) parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) common_billing_account_path = staticmethod( @@ -691,6 +701,151 @@ async def lookup_environment_history( # Done; return the response. return response + async def run_continuous_test( + self, + request: environment.RunContinuousTestRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestRequest`): + The request object. The request message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestResponse` + The response message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + + """ + # Create or coerce a protobuf request object. + request = environment.RunContinuousTestRequest(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.run_continuous_test, + default_timeout=None, + client_info=DEFAULT_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", request.environment),) + ), + ) + + # 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, + environment.RunContinuousTestResponse, + metadata_type=environment.RunContinuousTestMetadata, + ) + + # Done; return the response. + return response + + async def list_continuous_test_results( + self, + request: environment.ListContinuousTestResultsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContinuousTestResultsAsyncPager: + r"""Fetches a list of continuous test results for a given + environment. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest`): + The request object. The request message for + [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3beta1.Environments.ListContinuousTestResults]. + parent (:class:`str`): + Required. The environment to list results for. Format: + ``projects//locations//agents// 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.environments.pagers.ListContinuousTestResultsAsyncPager: + The response message for + [Environments.ListTestCaseResults][]. + + 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.ListContinuousTestResultsRequest(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_continuous_test_results, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(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.ListContinuousTestResultsAsyncPager( + 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/dialogflowcx_v3beta1/services/environments/client.py b/google/cloud/dialogflowcx_v3beta1/services/environments/client.py index a3ec88d7..9fc5a264 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/client.py @@ -161,6 +161,32 @@ def transport(self) -> EnvironmentsTransport: """ return self._transport + @staticmethod + def continuous_test_result_path( + project: str, + location: str, + agent: str, + environment: str, + continuous_test_result: str, + ) -> str: + """Returns a fully-qualified continuous_test_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/continuousTestResults/{continuous_test_result}".format( + project=project, + location=location, + agent=agent, + environment=environment, + continuous_test_result=continuous_test_result, + ) + + @staticmethod + def parse_continuous_test_result_path(path: str) -> Dict[str, str]: + """Parses a continuous_test_result path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/continuousTestResults/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def environment_path( project: str, location: str, agent: str, environment: str, @@ -179,6 +205,28 @@ def parse_environment_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def test_case_result_path( + project: str, location: str, agent: str, test_case: str, result: str, + ) -> str: + """Returns a fully-qualified test_case_result string.""" + return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( + project=project, + location=location, + agent=agent, + test_case=test_case, + result=result, + ) + + @staticmethod + def parse_test_case_result_path(path: str) -> Dict[str, str]: + """Parses a test_case_result path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def version_path( project: str, location: str, agent: str, flow: str, version: str, @@ -898,6 +946,154 @@ def lookup_environment_history( # Done; return the response. return response + def run_continuous_test( + self, + request: environment.RunContinuousTestRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestRequest): + The request object. The request message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestResponse` + The response message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.RunContinuousTestRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.RunContinuousTestRequest): + request = environment.RunContinuousTestRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_continuous_test] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("environment", request.environment),) + ), + ) + + # 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, + environment.RunContinuousTestResponse, + metadata_type=environment.RunContinuousTestMetadata, + ) + + # Done; return the response. + return response + + def list_continuous_test_results( + self, + request: environment.ListContinuousTestResultsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListContinuousTestResultsPager: + r"""Fetches a list of continuous test results for a given + environment. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest): + The request object. The request message for + [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3beta1.Environments.ListContinuousTestResults]. + parent (str): + Required. The environment to list results for. Format: + ``projects//locations//agents// 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflowcx_v3beta1.services.environments.pagers.ListContinuousTestResultsPager: + The response message for + [Environments.ListTestCaseResults][]. + + 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.ListContinuousTestResultsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.ListContinuousTestResultsRequest): + request = environment.ListContinuousTestResultsRequest(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_continuous_test_results + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListContinuousTestResultsPager( + 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/dialogflowcx_v3beta1/services/environments/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py index 53d80e94..7a03d756 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py @@ -283,3 +283,133 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListContinuousTestResultsPager: + """A pager for iterating through ``list_continuous_test_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``continuous_test_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListContinuousTestResults`` requests and continue to iterate + through the ``continuous_test_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` + 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.ListContinuousTestResultsResponse], + request: environment.ListContinuousTestResultsRequest, + response: environment.ListContinuousTestResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse): + 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.ListContinuousTestResultsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[environment.ListContinuousTestResultsResponse]: + 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.ContinuousTestResult]: + for page in self.pages: + yield from page.continuous_test_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListContinuousTestResultsAsyncPager: + """A pager for iterating through ``list_continuous_test_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``continuous_test_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListContinuousTestResults`` requests and continue to iterate + through the ``continuous_test_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` + 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.ListContinuousTestResultsResponse]], + request: environment.ListContinuousTestResultsRequest, + response: environment.ListContinuousTestResultsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest): + The initial request object. + response (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse): + 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.ListContinuousTestResultsRequest(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.ListContinuousTestResultsResponse]: + 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.ContinuousTestResult]: + async def async_generator(): + async for page in self.pages: + for response in page.continuous_test_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py index 8ddda462..697d55f9 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py @@ -193,6 +193,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.run_continuous_test: gapic_v1.method.wrap_method( + self.run_continuous_test, default_timeout=None, client_info=client_info, + ), + self.list_continuous_test_results: gapic_v1.method.wrap_method( + self.list_continuous_test_results, + default_timeout=None, + client_info=client_info, + ), } @property @@ -260,5 +268,26 @@ def lookup_environment_history( ]: raise NotImplementedError() + @property + def run_continuous_test( + self, + ) -> Callable[ + [environment.RunContinuousTestRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_continuous_test_results( + self, + ) -> Callable[ + [environment.ListContinuousTestResultsRequest], + Union[ + environment.ListContinuousTestResultsResponse, + Awaitable[environment.ListContinuousTestResultsResponse], + ], + ]: + raise NotImplementedError() + __all__ = ("EnvironmentsTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py index 01aac0ae..6d0a6c9a 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py @@ -413,5 +413,62 @@ def lookup_environment_history( ) return self._stubs["lookup_environment_history"] + @property + def run_continuous_test( + self, + ) -> Callable[[environment.RunContinuousTestRequest], operations_pb2.Operation]: + r"""Return a callable for the run continuous test method over gRPC. + + Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.RunContinuousTestRequest], + ~.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 "run_continuous_test" not in self._stubs: + self._stubs["run_continuous_test"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Environments/RunContinuousTest", + request_serializer=environment.RunContinuousTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["run_continuous_test"] + + @property + def list_continuous_test_results( + self, + ) -> Callable[ + [environment.ListContinuousTestResultsRequest], + environment.ListContinuousTestResultsResponse, + ]: + r"""Return a callable for the list continuous test results method over gRPC. + + Fetches a list of continuous test results for a given + environment. + + Returns: + Callable[[~.ListContinuousTestResultsRequest], + ~.ListContinuousTestResultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_continuous_test_results" not in self._stubs: + self._stubs["list_continuous_test_results"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Environments/ListContinuousTestResults", + request_serializer=environment.ListContinuousTestResultsRequest.serialize, + response_deserializer=environment.ListContinuousTestResultsResponse.deserialize, + ) + return self._stubs["list_continuous_test_results"] + __all__ = ("EnvironmentsGrpcTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py index 10474950..da9d3392 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py @@ -421,5 +421,64 @@ def lookup_environment_history( ) return self._stubs["lookup_environment_history"] + @property + def run_continuous_test( + self, + ) -> Callable[ + [environment.RunContinuousTestRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the run continuous test method over gRPC. + + Kicks off a continuous test under the specified + [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. + + Returns: + Callable[[~.RunContinuousTestRequest], + 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 "run_continuous_test" not in self._stubs: + self._stubs["run_continuous_test"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Environments/RunContinuousTest", + request_serializer=environment.RunContinuousTestRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["run_continuous_test"] + + @property + def list_continuous_test_results( + self, + ) -> Callable[ + [environment.ListContinuousTestResultsRequest], + Awaitable[environment.ListContinuousTestResultsResponse], + ]: + r"""Return a callable for the list continuous test results method over gRPC. + + Fetches a list of continuous test results for a given + environment. + + Returns: + Callable[[~.ListContinuousTestResultsRequest], + Awaitable[~.ListContinuousTestResultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_continuous_test_results" not in self._stubs: + self._stubs["list_continuous_test_results"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Environments/ListContinuousTestResults", + request_serializer=environment.ListContinuousTestResultsRequest.serialize, + response_deserializer=environment.ListContinuousTestResultsResponse.deserialize, + ) + return self._stubs["list_continuous_test_results"] + __all__ = ("EnvironmentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/types/__init__.py b/google/cloud/dialogflowcx_v3beta1/types/__init__.py index 00da5907..c083e5b6 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/types/__init__.py @@ -50,14 +50,20 @@ UpdateEntityTypeRequest, ) from .environment import ( + ContinuousTestResult, CreateEnvironmentRequest, DeleteEnvironmentRequest, Environment, GetEnvironmentRequest, + ListContinuousTestResultsRequest, + ListContinuousTestResultsResponse, ListEnvironmentsRequest, ListEnvironmentsResponse, LookupEnvironmentHistoryRequest, LookupEnvironmentHistoryResponse, + RunContinuousTestMetadata, + RunContinuousTestRequest, + RunContinuousTestResponse, UpdateEnvironmentRequest, ) from .experiment import ( @@ -259,14 +265,20 @@ "ListEntityTypesRequest", "ListEntityTypesResponse", "UpdateEntityTypeRequest", + "ContinuousTestResult", "CreateEnvironmentRequest", "DeleteEnvironmentRequest", "Environment", "GetEnvironmentRequest", + "ListContinuousTestResultsRequest", + "ListContinuousTestResultsResponse", "ListEnvironmentsRequest", "ListEnvironmentsResponse", "LookupEnvironmentHistoryRequest", "LookupEnvironmentHistoryResponse", + "RunContinuousTestMetadata", + "RunContinuousTestRequest", + "RunContinuousTestResponse", "UpdateEnvironmentRequest", "CreateExperimentRequest", "DeleteExperimentRequest", diff --git a/google/cloud/dialogflowcx_v3beta1/types/environment.py b/google/cloud/dialogflowcx_v3beta1/types/environment.py index f48c77a9..4d47818d 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/environment.py +++ b/google/cloud/dialogflowcx_v3beta1/types/environment.py @@ -15,6 +15,7 @@ # import proto # type: ignore +from google.cloud.dialogflowcx_v3beta1.types import test_case from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore @@ -31,6 +32,12 @@ "DeleteEnvironmentRequest", "LookupEnvironmentHistoryRequest", "LookupEnvironmentHistoryResponse", + "ContinuousTestResult", + "RunContinuousTestRequest", + "RunContinuousTestResponse", + "RunContinuousTestMetadata", + "ListContinuousTestResultsRequest", + "ListContinuousTestResultsResponse", }, ) @@ -248,4 +255,119 @@ def raw_page(self): next_page_token = proto.Field(proto.STRING, number=2,) +class ContinuousTestResult(proto.Message): + r"""Represents a result from running a test case in an agent + environment. + + Attributes: + name (str): + The resource name for the continuous test result. Format: + ``projects//locations//agents//environments//continuousTestResults/``. + result (google.cloud.dialogflowcx_v3beta1.types.ContinuousTestResult.AggregatedTestResult): + The result of this continuous test run, i.e. + whether all the tests in this continuous test + run pass or not. + test_case_results (Sequence[str]): + A list of individual test case results names + in this continuous test run. + run_time (google.protobuf.timestamp_pb2.Timestamp): + Time when the continuous testing run starts. + """ + + class AggregatedTestResult(proto.Enum): + r"""The overall result for a continuous test run in an agent + environment. + """ + AGGREGATED_TEST_RESULT_UNSPECIFIED = 0 + PASSED = 1 + FAILED = 2 + + name = proto.Field(proto.STRING, number=1,) + result = proto.Field(proto.ENUM, number=2, enum=AggregatedTestResult,) + test_case_results = proto.RepeatedField(proto.STRING, number=3,) + run_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + + +class RunContinuousTestRequest(proto.Message): + r"""The request message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + + Attributes: + environment (str): + Required. Format: + ``projects//locations//agents//environments/``. + """ + + environment = proto.Field(proto.STRING, number=1,) + + +class RunContinuousTestResponse(proto.Message): + r"""The response message for + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. + + Attributes: + continuous_test_result (google.cloud.dialogflowcx_v3beta1.types.ContinuousTestResult): + The result for a continuous test run. + """ + + continuous_test_result = proto.Field( + proto.MESSAGE, number=1, message="ContinuousTestResult", + ) + + +class RunContinuousTestMetadata(proto.Message): + r"""Metadata returned for the + [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest] + long running operation. + + Attributes: + errors (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestError]): + The test errors. + """ + + errors = proto.RepeatedField(proto.MESSAGE, number=1, message=test_case.TestError,) + + +class ListContinuousTestResultsRequest(proto.Message): + r"""The request message for + [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3beta1.Environments.ListContinuousTestResults]. + + Attributes: + parent (str): + Required. The environment to list results for. Format: + ``projects//locations//agents// environments/``. + 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 ListContinuousTestResultsResponse(proto.Message): + r"""The response message for [Environments.ListTestCaseResults][]. + Attributes: + continuous_test_results (Sequence[google.cloud.dialogflowcx_v3beta1.types.ContinuousTestResult]): + The list of continuous test results. + 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 + + continuous_test_results = proto.RepeatedField( + proto.MESSAGE, number=1, message="ContinuousTestResult", + ) + next_page_token = proto.Field(proto.STRING, number=2,) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/MANIFEST.in b/owl-bot-staging/v3/MANIFEST.in deleted file mode 100644 index 83900298..00000000 --- a/owl-bot-staging/v3/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/dialogflowcx *.py -recursive-include google/cloud/dialogflowcx_v3 *.py diff --git a/owl-bot-staging/v3/README.rst b/owl-bot-staging/v3/README.rst deleted file mode 100644 index bfe57a44..00000000 --- a/owl-bot-staging/v3/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Dialogflowcx 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 Dialogflowcx 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/v3/docs/conf.py b/owl-bot-staging/v3/docs/conf.py deleted file mode 100644 index 814121cd..00000000 --- a/owl-bot-staging/v3/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-dialogflowcx 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-dialogflowcx" -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-dialogflowcx-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-dialogflowcx.tex", - u"google-cloud-dialogflowcx 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-dialogflowcx", - u"Google Cloud Dialogflowcx 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-dialogflowcx", - u"google-cloud-dialogflowcx Documentation", - author, - "google-cloud-dialogflowcx", - "GAPIC library for Google Cloud Dialogflowcx 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/v3/docs/dialogflowcx_v3/agents.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/agents.rst deleted file mode 100644 index 4deb1730..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/agents.rst +++ /dev/null @@ -1,10 +0,0 @@ -Agents ------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3.services.agents - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.agents.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst deleted file mode 100644 index 08e4b6e8..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/entity_types.rst +++ /dev/null @@ -1,10 +0,0 @@ -EntityTypes ------------------------------ - -.. automodule:: google.cloud.dialogflowcx_v3.services.entity_types - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.entity_types.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst deleted file mode 100644 index 246ee15a..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/environments.rst +++ /dev/null @@ -1,10 +0,0 @@ -Environments ------------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3.services.environments - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.environments.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst deleted file mode 100644 index 5cba0e2a..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/experiments.rst +++ /dev/null @@ -1,10 +0,0 @@ -Experiments ------------------------------ - -.. automodule:: google.cloud.dialogflowcx_v3.services.experiments - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.experiments.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst deleted file mode 100644 index 77f6398e..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/flows.rst +++ /dev/null @@ -1,10 +0,0 @@ -Flows ------------------------ - -.. automodule:: google.cloud.dialogflowcx_v3.services.flows - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.flows.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst deleted file mode 100644 index 8b9e6dda..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/intents.rst +++ /dev/null @@ -1,10 +0,0 @@ -Intents -------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3.services.intents - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.intents.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst deleted file mode 100644 index 0bbfbced..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/pages.rst +++ /dev/null @@ -1,10 +0,0 @@ -Pages ------------------------ - -.. automodule:: google.cloud.dialogflowcx_v3.services.pages - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.pages.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst deleted file mode 100644 index 4b4fa007..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/security_settings_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecuritySettingsService ------------------------------------------ - -.. automodule:: google.cloud.dialogflowcx_v3.services.security_settings_service - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.security_settings_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst deleted file mode 100644 index 3da663c9..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/services.rst +++ /dev/null @@ -1,19 +0,0 @@ -Services for Google Cloud Dialogflowcx v3 API -============================================= -.. toctree:: - :maxdepth: 2 - - agents - entity_types - environments - experiments - flows - intents - pages - security_settings_service - session_entity_types - sessions - test_cases - transition_route_groups - versions - webhooks diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst deleted file mode 100644 index 46ff0f6e..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/session_entity_types.rst +++ /dev/null @@ -1,10 +0,0 @@ -SessionEntityTypes ------------------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3.services.session_entity_types - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.session_entity_types.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst deleted file mode 100644 index 494bceb1..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/sessions.rst +++ /dev/null @@ -1,6 +0,0 @@ -Sessions --------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3.services.sessions - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst deleted file mode 100644 index 3cad4dd4..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/test_cases.rst +++ /dev/null @@ -1,10 +0,0 @@ -TestCases ---------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3.services.test_cases - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.test_cases.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst deleted file mode 100644 index d5549da9..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/transition_route_groups.rst +++ /dev/null @@ -1,10 +0,0 @@ -TransitionRouteGroups ---------------------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3.services.transition_route_groups - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.transition_route_groups.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst deleted file mode 100644 index 7e2b1c53..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Dialogflowcx v3 API -========================================== - -.. automodule:: google.cloud.dialogflowcx_v3.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst deleted file mode 100644 index 2d72f02d..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/versions.rst +++ /dev/null @@ -1,10 +0,0 @@ -Versions --------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3.services.versions - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.versions.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst b/owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst deleted file mode 100644 index 2e2f9b8c..00000000 --- a/owl-bot-staging/v3/docs/dialogflowcx_v3/webhooks.rst +++ /dev/null @@ -1,10 +0,0 @@ -Webhooks --------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3.services.webhooks - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3.services.webhooks.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3/docs/index.rst b/owl-bot-staging/v3/docs/index.rst deleted file mode 100644 index eaab73b8..00000000 --- a/owl-bot-staging/v3/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - dialogflowcx_v3/services - dialogflowcx_v3/types diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py deleted file mode 100644 index 9e9c5117..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx/__init__.py +++ /dev/null @@ -1,439 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.agents.client import AgentsClient -from google.cloud.dialogflowcx_v3.services.agents.async_client import AgentsAsyncClient -from google.cloud.dialogflowcx_v3.services.entity_types.client import EntityTypesClient -from google.cloud.dialogflowcx_v3.services.entity_types.async_client import EntityTypesAsyncClient -from google.cloud.dialogflowcx_v3.services.environments.client import EnvironmentsClient -from google.cloud.dialogflowcx_v3.services.environments.async_client import EnvironmentsAsyncClient -from google.cloud.dialogflowcx_v3.services.experiments.client import ExperimentsClient -from google.cloud.dialogflowcx_v3.services.experiments.async_client import ExperimentsAsyncClient -from google.cloud.dialogflowcx_v3.services.flows.client import FlowsClient -from google.cloud.dialogflowcx_v3.services.flows.async_client import FlowsAsyncClient -from google.cloud.dialogflowcx_v3.services.intents.client import IntentsClient -from google.cloud.dialogflowcx_v3.services.intents.async_client import IntentsAsyncClient -from google.cloud.dialogflowcx_v3.services.pages.client import PagesClient -from google.cloud.dialogflowcx_v3.services.pages.async_client import PagesAsyncClient -from google.cloud.dialogflowcx_v3.services.security_settings_service.client import SecuritySettingsServiceClient -from google.cloud.dialogflowcx_v3.services.security_settings_service.async_client import SecuritySettingsServiceAsyncClient -from google.cloud.dialogflowcx_v3.services.session_entity_types.client import SessionEntityTypesClient -from google.cloud.dialogflowcx_v3.services.session_entity_types.async_client import SessionEntityTypesAsyncClient -from google.cloud.dialogflowcx_v3.services.sessions.client import SessionsClient -from google.cloud.dialogflowcx_v3.services.sessions.async_client import SessionsAsyncClient -from google.cloud.dialogflowcx_v3.services.test_cases.client import TestCasesClient -from google.cloud.dialogflowcx_v3.services.test_cases.async_client import TestCasesAsyncClient -from google.cloud.dialogflowcx_v3.services.transition_route_groups.client import TransitionRouteGroupsClient -from google.cloud.dialogflowcx_v3.services.transition_route_groups.async_client import TransitionRouteGroupsAsyncClient -from google.cloud.dialogflowcx_v3.services.versions.client import VersionsClient -from google.cloud.dialogflowcx_v3.services.versions.async_client import VersionsAsyncClient -from google.cloud.dialogflowcx_v3.services.webhooks.client import WebhooksClient -from google.cloud.dialogflowcx_v3.services.webhooks.async_client import WebhooksAsyncClient - -from google.cloud.dialogflowcx_v3.types.agent import Agent -from google.cloud.dialogflowcx_v3.types.agent import AgentValidationResult -from google.cloud.dialogflowcx_v3.types.agent import CreateAgentRequest -from google.cloud.dialogflowcx_v3.types.agent import DeleteAgentRequest -from google.cloud.dialogflowcx_v3.types.agent import ExportAgentRequest -from google.cloud.dialogflowcx_v3.types.agent import ExportAgentResponse -from google.cloud.dialogflowcx_v3.types.agent import GetAgentRequest -from google.cloud.dialogflowcx_v3.types.agent import GetAgentValidationResultRequest -from google.cloud.dialogflowcx_v3.types.agent import ListAgentsRequest -from google.cloud.dialogflowcx_v3.types.agent import ListAgentsResponse -from google.cloud.dialogflowcx_v3.types.agent import RestoreAgentRequest -from google.cloud.dialogflowcx_v3.types.agent import SpeechToTextSettings -from google.cloud.dialogflowcx_v3.types.agent import UpdateAgentRequest -from google.cloud.dialogflowcx_v3.types.agent import ValidateAgentRequest -from google.cloud.dialogflowcx_v3.types.audio_config import InputAudioConfig -from google.cloud.dialogflowcx_v3.types.audio_config import OutputAudioConfig -from google.cloud.dialogflowcx_v3.types.audio_config import SpeechWordInfo -from google.cloud.dialogflowcx_v3.types.audio_config import SynthesizeSpeechConfig -from google.cloud.dialogflowcx_v3.types.audio_config import VoiceSelectionParams -from google.cloud.dialogflowcx_v3.types.audio_config import AudioEncoding -from google.cloud.dialogflowcx_v3.types.audio_config import OutputAudioEncoding -from google.cloud.dialogflowcx_v3.types.audio_config import SpeechModelVariant -from google.cloud.dialogflowcx_v3.types.audio_config import SsmlVoiceGender -from google.cloud.dialogflowcx_v3.types.entity_type import CreateEntityTypeRequest -from google.cloud.dialogflowcx_v3.types.entity_type import DeleteEntityTypeRequest -from google.cloud.dialogflowcx_v3.types.entity_type import EntityType -from google.cloud.dialogflowcx_v3.types.entity_type import GetEntityTypeRequest -from google.cloud.dialogflowcx_v3.types.entity_type import ListEntityTypesRequest -from google.cloud.dialogflowcx_v3.types.entity_type import ListEntityTypesResponse -from google.cloud.dialogflowcx_v3.types.entity_type import UpdateEntityTypeRequest -from google.cloud.dialogflowcx_v3.types.environment import CreateEnvironmentRequest -from google.cloud.dialogflowcx_v3.types.environment import DeleteEnvironmentRequest -from google.cloud.dialogflowcx_v3.types.environment import Environment -from google.cloud.dialogflowcx_v3.types.environment import GetEnvironmentRequest -from google.cloud.dialogflowcx_v3.types.environment import ListEnvironmentsRequest -from google.cloud.dialogflowcx_v3.types.environment import ListEnvironmentsResponse -from google.cloud.dialogflowcx_v3.types.environment import LookupEnvironmentHistoryRequest -from google.cloud.dialogflowcx_v3.types.environment import LookupEnvironmentHistoryResponse -from google.cloud.dialogflowcx_v3.types.environment import UpdateEnvironmentRequest -from google.cloud.dialogflowcx_v3.types.experiment import CreateExperimentRequest -from google.cloud.dialogflowcx_v3.types.experiment import DeleteExperimentRequest -from google.cloud.dialogflowcx_v3.types.experiment import Experiment -from google.cloud.dialogflowcx_v3.types.experiment import GetExperimentRequest -from google.cloud.dialogflowcx_v3.types.experiment import ListExperimentsRequest -from google.cloud.dialogflowcx_v3.types.experiment import ListExperimentsResponse -from google.cloud.dialogflowcx_v3.types.experiment import StartExperimentRequest -from google.cloud.dialogflowcx_v3.types.experiment import StopExperimentRequest -from google.cloud.dialogflowcx_v3.types.experiment import UpdateExperimentRequest -from google.cloud.dialogflowcx_v3.types.experiment import VariantsHistory -from google.cloud.dialogflowcx_v3.types.experiment import VersionVariants -from google.cloud.dialogflowcx_v3.types.flow import CreateFlowRequest -from google.cloud.dialogflowcx_v3.types.flow import DeleteFlowRequest -from google.cloud.dialogflowcx_v3.types.flow import ExportFlowRequest -from google.cloud.dialogflowcx_v3.types.flow import ExportFlowResponse -from google.cloud.dialogflowcx_v3.types.flow import Flow -from google.cloud.dialogflowcx_v3.types.flow import FlowValidationResult -from google.cloud.dialogflowcx_v3.types.flow import GetFlowRequest -from google.cloud.dialogflowcx_v3.types.flow import GetFlowValidationResultRequest -from google.cloud.dialogflowcx_v3.types.flow import ImportFlowRequest -from google.cloud.dialogflowcx_v3.types.flow import ImportFlowResponse -from google.cloud.dialogflowcx_v3.types.flow import ListFlowsRequest -from google.cloud.dialogflowcx_v3.types.flow import ListFlowsResponse -from google.cloud.dialogflowcx_v3.types.flow import NluSettings -from google.cloud.dialogflowcx_v3.types.flow import TrainFlowRequest -from google.cloud.dialogflowcx_v3.types.flow import UpdateFlowRequest -from google.cloud.dialogflowcx_v3.types.flow import ValidateFlowRequest -from google.cloud.dialogflowcx_v3.types.fulfillment import Fulfillment -from google.cloud.dialogflowcx_v3.types.intent import CreateIntentRequest -from google.cloud.dialogflowcx_v3.types.intent import DeleteIntentRequest -from google.cloud.dialogflowcx_v3.types.intent import GetIntentRequest -from google.cloud.dialogflowcx_v3.types.intent import Intent -from google.cloud.dialogflowcx_v3.types.intent import ListIntentsRequest -from google.cloud.dialogflowcx_v3.types.intent import ListIntentsResponse -from google.cloud.dialogflowcx_v3.types.intent import UpdateIntentRequest -from google.cloud.dialogflowcx_v3.types.intent import IntentView -from google.cloud.dialogflowcx_v3.types.page import CreatePageRequest -from google.cloud.dialogflowcx_v3.types.page import DeletePageRequest -from google.cloud.dialogflowcx_v3.types.page import EventHandler -from google.cloud.dialogflowcx_v3.types.page import Form -from google.cloud.dialogflowcx_v3.types.page import GetPageRequest -from google.cloud.dialogflowcx_v3.types.page import ListPagesRequest -from google.cloud.dialogflowcx_v3.types.page import ListPagesResponse -from google.cloud.dialogflowcx_v3.types.page import Page -from google.cloud.dialogflowcx_v3.types.page import TransitionRoute -from google.cloud.dialogflowcx_v3.types.page import UpdatePageRequest -from google.cloud.dialogflowcx_v3.types.response_message import ResponseMessage -from google.cloud.dialogflowcx_v3.types.security_settings import CreateSecuritySettingsRequest -from google.cloud.dialogflowcx_v3.types.security_settings import DeleteSecuritySettingsRequest -from google.cloud.dialogflowcx_v3.types.security_settings import GetSecuritySettingsRequest -from google.cloud.dialogflowcx_v3.types.security_settings import ListSecuritySettingsRequest -from google.cloud.dialogflowcx_v3.types.security_settings import ListSecuritySettingsResponse -from google.cloud.dialogflowcx_v3.types.security_settings import SecuritySettings -from google.cloud.dialogflowcx_v3.types.security_settings import UpdateSecuritySettingsRequest -from google.cloud.dialogflowcx_v3.types.session import AudioInput -from google.cloud.dialogflowcx_v3.types.session import DetectIntentRequest -from google.cloud.dialogflowcx_v3.types.session import DetectIntentResponse -from google.cloud.dialogflowcx_v3.types.session import DtmfInput -from google.cloud.dialogflowcx_v3.types.session import EventInput -from google.cloud.dialogflowcx_v3.types.session import FulfillIntentRequest -from google.cloud.dialogflowcx_v3.types.session import FulfillIntentResponse -from google.cloud.dialogflowcx_v3.types.session import IntentInput -from google.cloud.dialogflowcx_v3.types.session import Match -from google.cloud.dialogflowcx_v3.types.session import MatchIntentRequest -from google.cloud.dialogflowcx_v3.types.session import MatchIntentResponse -from google.cloud.dialogflowcx_v3.types.session import QueryInput -from google.cloud.dialogflowcx_v3.types.session import QueryParameters -from google.cloud.dialogflowcx_v3.types.session import QueryResult -from google.cloud.dialogflowcx_v3.types.session import SentimentAnalysisResult -from google.cloud.dialogflowcx_v3.types.session import StreamingDetectIntentRequest -from google.cloud.dialogflowcx_v3.types.session import StreamingDetectIntentResponse -from google.cloud.dialogflowcx_v3.types.session import StreamingRecognitionResult -from google.cloud.dialogflowcx_v3.types.session import TextInput -from google.cloud.dialogflowcx_v3.types.session_entity_type import CreateSessionEntityTypeRequest -from google.cloud.dialogflowcx_v3.types.session_entity_type import DeleteSessionEntityTypeRequest -from google.cloud.dialogflowcx_v3.types.session_entity_type import GetSessionEntityTypeRequest -from google.cloud.dialogflowcx_v3.types.session_entity_type import ListSessionEntityTypesRequest -from google.cloud.dialogflowcx_v3.types.session_entity_type import ListSessionEntityTypesResponse -from google.cloud.dialogflowcx_v3.types.session_entity_type import SessionEntityType -from google.cloud.dialogflowcx_v3.types.session_entity_type import UpdateSessionEntityTypeRequest -from google.cloud.dialogflowcx_v3.types.test_case import BatchDeleteTestCasesRequest -from google.cloud.dialogflowcx_v3.types.test_case import BatchRunTestCasesMetadata -from google.cloud.dialogflowcx_v3.types.test_case import BatchRunTestCasesRequest -from google.cloud.dialogflowcx_v3.types.test_case import BatchRunTestCasesResponse -from google.cloud.dialogflowcx_v3.types.test_case import CalculateCoverageRequest -from google.cloud.dialogflowcx_v3.types.test_case import CalculateCoverageResponse -from google.cloud.dialogflowcx_v3.types.test_case import ConversationTurn -from google.cloud.dialogflowcx_v3.types.test_case import CreateTestCaseRequest -from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesMetadata -from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesRequest -from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesResponse -from google.cloud.dialogflowcx_v3.types.test_case import GetTestCaseRequest -from google.cloud.dialogflowcx_v3.types.test_case import GetTestCaseResultRequest -from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesMetadata -from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesRequest -from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesResponse -from google.cloud.dialogflowcx_v3.types.test_case import IntentCoverage -from google.cloud.dialogflowcx_v3.types.test_case import ListTestCaseResultsRequest -from google.cloud.dialogflowcx_v3.types.test_case import ListTestCaseResultsResponse -from google.cloud.dialogflowcx_v3.types.test_case import ListTestCasesRequest -from google.cloud.dialogflowcx_v3.types.test_case import ListTestCasesResponse -from google.cloud.dialogflowcx_v3.types.test_case import RunTestCaseMetadata -from google.cloud.dialogflowcx_v3.types.test_case import RunTestCaseRequest -from google.cloud.dialogflowcx_v3.types.test_case import RunTestCaseResponse -from google.cloud.dialogflowcx_v3.types.test_case import TestCase -from google.cloud.dialogflowcx_v3.types.test_case import TestCaseError -from google.cloud.dialogflowcx_v3.types.test_case import TestCaseResult -from google.cloud.dialogflowcx_v3.types.test_case import TestConfig -from google.cloud.dialogflowcx_v3.types.test_case import TestError -from google.cloud.dialogflowcx_v3.types.test_case import TestRunDifference -from google.cloud.dialogflowcx_v3.types.test_case import TransitionCoverage -from google.cloud.dialogflowcx_v3.types.test_case import TransitionRouteGroupCoverage -from google.cloud.dialogflowcx_v3.types.test_case import UpdateTestCaseRequest -from google.cloud.dialogflowcx_v3.types.test_case import TestResult -from google.cloud.dialogflowcx_v3.types.transition_route_group import CreateTransitionRouteGroupRequest -from google.cloud.dialogflowcx_v3.types.transition_route_group import DeleteTransitionRouteGroupRequest -from google.cloud.dialogflowcx_v3.types.transition_route_group import GetTransitionRouteGroupRequest -from google.cloud.dialogflowcx_v3.types.transition_route_group import ListTransitionRouteGroupsRequest -from google.cloud.dialogflowcx_v3.types.transition_route_group import ListTransitionRouteGroupsResponse -from google.cloud.dialogflowcx_v3.types.transition_route_group import TransitionRouteGroup -from google.cloud.dialogflowcx_v3.types.transition_route_group import UpdateTransitionRouteGroupRequest -from google.cloud.dialogflowcx_v3.types.validation_message import ResourceName -from google.cloud.dialogflowcx_v3.types.validation_message import ValidationMessage -from google.cloud.dialogflowcx_v3.types.version import CreateVersionOperationMetadata -from google.cloud.dialogflowcx_v3.types.version import CreateVersionRequest -from google.cloud.dialogflowcx_v3.types.version import DeleteVersionRequest -from google.cloud.dialogflowcx_v3.types.version import GetVersionRequest -from google.cloud.dialogflowcx_v3.types.version import ListVersionsRequest -from google.cloud.dialogflowcx_v3.types.version import ListVersionsResponse -from google.cloud.dialogflowcx_v3.types.version import LoadVersionRequest -from google.cloud.dialogflowcx_v3.types.version import UpdateVersionRequest -from google.cloud.dialogflowcx_v3.types.version import Version -from google.cloud.dialogflowcx_v3.types.webhook import CreateWebhookRequest -from google.cloud.dialogflowcx_v3.types.webhook import DeleteWebhookRequest -from google.cloud.dialogflowcx_v3.types.webhook import GetWebhookRequest -from google.cloud.dialogflowcx_v3.types.webhook import ListWebhooksRequest -from google.cloud.dialogflowcx_v3.types.webhook import ListWebhooksResponse -from google.cloud.dialogflowcx_v3.types.webhook import PageInfo -from google.cloud.dialogflowcx_v3.types.webhook import SessionInfo -from google.cloud.dialogflowcx_v3.types.webhook import UpdateWebhookRequest -from google.cloud.dialogflowcx_v3.types.webhook import Webhook -from google.cloud.dialogflowcx_v3.types.webhook import WebhookRequest -from google.cloud.dialogflowcx_v3.types.webhook import WebhookResponse - -__all__ = ('AgentsClient', - 'AgentsAsyncClient', - 'EntityTypesClient', - 'EntityTypesAsyncClient', - 'EnvironmentsClient', - 'EnvironmentsAsyncClient', - 'ExperimentsClient', - 'ExperimentsAsyncClient', - 'FlowsClient', - 'FlowsAsyncClient', - 'IntentsClient', - 'IntentsAsyncClient', - 'PagesClient', - 'PagesAsyncClient', - 'SecuritySettingsServiceClient', - 'SecuritySettingsServiceAsyncClient', - 'SessionEntityTypesClient', - 'SessionEntityTypesAsyncClient', - 'SessionsClient', - 'SessionsAsyncClient', - 'TestCasesClient', - 'TestCasesAsyncClient', - 'TransitionRouteGroupsClient', - 'TransitionRouteGroupsAsyncClient', - 'VersionsClient', - 'VersionsAsyncClient', - 'WebhooksClient', - 'WebhooksAsyncClient', - 'Agent', - 'AgentValidationResult', - 'CreateAgentRequest', - 'DeleteAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'GetAgentRequest', - 'GetAgentValidationResultRequest', - 'ListAgentsRequest', - 'ListAgentsResponse', - 'RestoreAgentRequest', - 'SpeechToTextSettings', - 'UpdateAgentRequest', - 'ValidateAgentRequest', - 'InputAudioConfig', - 'OutputAudioConfig', - 'SpeechWordInfo', - 'SynthesizeSpeechConfig', - 'VoiceSelectionParams', - 'AudioEncoding', - 'OutputAudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'CreateEntityTypeRequest', - 'DeleteEntityTypeRequest', - 'EntityType', - 'GetEntityTypeRequest', - 'ListEntityTypesRequest', - 'ListEntityTypesResponse', - 'UpdateEntityTypeRequest', - 'CreateEnvironmentRequest', - 'DeleteEnvironmentRequest', - 'Environment', - 'GetEnvironmentRequest', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LookupEnvironmentHistoryRequest', - 'LookupEnvironmentHistoryResponse', - 'UpdateEnvironmentRequest', - 'CreateExperimentRequest', - 'DeleteExperimentRequest', - 'Experiment', - 'GetExperimentRequest', - 'ListExperimentsRequest', - 'ListExperimentsResponse', - 'StartExperimentRequest', - 'StopExperimentRequest', - 'UpdateExperimentRequest', - 'VariantsHistory', - 'VersionVariants', - 'CreateFlowRequest', - 'DeleteFlowRequest', - 'ExportFlowRequest', - 'ExportFlowResponse', - 'Flow', - 'FlowValidationResult', - 'GetFlowRequest', - 'GetFlowValidationResultRequest', - 'ImportFlowRequest', - 'ImportFlowResponse', - 'ListFlowsRequest', - 'ListFlowsResponse', - 'NluSettings', - 'TrainFlowRequest', - 'UpdateFlowRequest', - 'ValidateFlowRequest', - 'Fulfillment', - 'CreateIntentRequest', - 'DeleteIntentRequest', - 'GetIntentRequest', - 'Intent', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'UpdateIntentRequest', - 'IntentView', - 'CreatePageRequest', - 'DeletePageRequest', - 'EventHandler', - 'Form', - 'GetPageRequest', - 'ListPagesRequest', - 'ListPagesResponse', - 'Page', - 'TransitionRoute', - 'UpdatePageRequest', - 'ResponseMessage', - 'CreateSecuritySettingsRequest', - 'DeleteSecuritySettingsRequest', - 'GetSecuritySettingsRequest', - 'ListSecuritySettingsRequest', - 'ListSecuritySettingsResponse', - 'SecuritySettings', - 'UpdateSecuritySettingsRequest', - 'AudioInput', - 'DetectIntentRequest', - 'DetectIntentResponse', - 'DtmfInput', - 'EventInput', - 'FulfillIntentRequest', - 'FulfillIntentResponse', - 'IntentInput', - 'Match', - 'MatchIntentRequest', - 'MatchIntentResponse', - 'QueryInput', - 'QueryParameters', - 'QueryResult', - 'SentimentAnalysisResult', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'TextInput', - 'CreateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - 'GetSessionEntityTypeRequest', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'SessionEntityType', - 'UpdateSessionEntityTypeRequest', - 'BatchDeleteTestCasesRequest', - 'BatchRunTestCasesMetadata', - 'BatchRunTestCasesRequest', - 'BatchRunTestCasesResponse', - 'CalculateCoverageRequest', - 'CalculateCoverageResponse', - 'ConversationTurn', - 'CreateTestCaseRequest', - 'ExportTestCasesMetadata', - 'ExportTestCasesRequest', - 'ExportTestCasesResponse', - 'GetTestCaseRequest', - 'GetTestCaseResultRequest', - 'ImportTestCasesMetadata', - 'ImportTestCasesRequest', - 'ImportTestCasesResponse', - 'IntentCoverage', - 'ListTestCaseResultsRequest', - 'ListTestCaseResultsResponse', - 'ListTestCasesRequest', - 'ListTestCasesResponse', - 'RunTestCaseMetadata', - 'RunTestCaseRequest', - 'RunTestCaseResponse', - 'TestCase', - 'TestCaseError', - 'TestCaseResult', - 'TestConfig', - 'TestError', - 'TestRunDifference', - 'TransitionCoverage', - 'TransitionRouteGroupCoverage', - 'UpdateTestCaseRequest', - 'TestResult', - 'CreateTransitionRouteGroupRequest', - 'DeleteTransitionRouteGroupRequest', - 'GetTransitionRouteGroupRequest', - 'ListTransitionRouteGroupsRequest', - 'ListTransitionRouteGroupsResponse', - 'TransitionRouteGroup', - 'UpdateTransitionRouteGroupRequest', - 'ResourceName', - 'ValidationMessage', - 'CreateVersionOperationMetadata', - 'CreateVersionRequest', - 'DeleteVersionRequest', - 'GetVersionRequest', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'LoadVersionRequest', - 'UpdateVersionRequest', - 'Version', - 'CreateWebhookRequest', - 'DeleteWebhookRequest', - 'GetWebhookRequest', - 'ListWebhooksRequest', - 'ListWebhooksResponse', - 'PageInfo', - 'SessionInfo', - 'UpdateWebhookRequest', - 'Webhook', - 'WebhookRequest', - 'WebhookResponse', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed b/owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed deleted file mode 100644 index 60fdca49..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-dialogflowcx package uses inline types. diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py deleted file mode 100644 index 50d0af79..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/__init__.py +++ /dev/null @@ -1,440 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.entity_types import EntityTypesClient -from .services.entity_types import EntityTypesAsyncClient -from .services.environments import EnvironmentsClient -from .services.environments import EnvironmentsAsyncClient -from .services.experiments import ExperimentsClient -from .services.experiments import ExperimentsAsyncClient -from .services.flows import FlowsClient -from .services.flows import FlowsAsyncClient -from .services.intents import IntentsClient -from .services.intents import IntentsAsyncClient -from .services.pages import PagesClient -from .services.pages import PagesAsyncClient -from .services.security_settings_service import SecuritySettingsServiceClient -from .services.security_settings_service import SecuritySettingsServiceAsyncClient -from .services.session_entity_types import SessionEntityTypesClient -from .services.session_entity_types import SessionEntityTypesAsyncClient -from .services.sessions import SessionsClient -from .services.sessions import SessionsAsyncClient -from .services.test_cases import TestCasesClient -from .services.test_cases import TestCasesAsyncClient -from .services.transition_route_groups import TransitionRouteGroupsClient -from .services.transition_route_groups import TransitionRouteGroupsAsyncClient -from .services.versions import VersionsClient -from .services.versions import VersionsAsyncClient -from .services.webhooks import WebhooksClient -from .services.webhooks import WebhooksAsyncClient - -from .types.agent import Agent -from .types.agent import AgentValidationResult -from .types.agent import CreateAgentRequest -from .types.agent import DeleteAgentRequest -from .types.agent import ExportAgentRequest -from .types.agent import ExportAgentResponse -from .types.agent import GetAgentRequest -from .types.agent import GetAgentValidationResultRequest -from .types.agent import ListAgentsRequest -from .types.agent import ListAgentsResponse -from .types.agent import RestoreAgentRequest -from .types.agent import SpeechToTextSettings -from .types.agent import UpdateAgentRequest -from .types.agent import ValidateAgentRequest -from .types.audio_config import InputAudioConfig -from .types.audio_config import OutputAudioConfig -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.entity_type import CreateEntityTypeRequest -from .types.entity_type import DeleteEntityTypeRequest -from .types.entity_type import EntityType -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 GetEnvironmentRequest -from .types.environment import ListEnvironmentsRequest -from .types.environment import ListEnvironmentsResponse -from .types.environment import LookupEnvironmentHistoryRequest -from .types.environment import LookupEnvironmentHistoryResponse -from .types.environment import UpdateEnvironmentRequest -from .types.experiment import CreateExperimentRequest -from .types.experiment import DeleteExperimentRequest -from .types.experiment import Experiment -from .types.experiment import GetExperimentRequest -from .types.experiment import ListExperimentsRequest -from .types.experiment import ListExperimentsResponse -from .types.experiment import StartExperimentRequest -from .types.experiment import StopExperimentRequest -from .types.experiment import UpdateExperimentRequest -from .types.experiment import VariantsHistory -from .types.experiment import VersionVariants -from .types.flow import CreateFlowRequest -from .types.flow import DeleteFlowRequest -from .types.flow import ExportFlowRequest -from .types.flow import ExportFlowResponse -from .types.flow import Flow -from .types.flow import FlowValidationResult -from .types.flow import GetFlowRequest -from .types.flow import GetFlowValidationResultRequest -from .types.flow import ImportFlowRequest -from .types.flow import ImportFlowResponse -from .types.flow import ListFlowsRequest -from .types.flow import ListFlowsResponse -from .types.flow import NluSettings -from .types.flow import TrainFlowRequest -from .types.flow import UpdateFlowRequest -from .types.flow import ValidateFlowRequest -from .types.fulfillment import Fulfillment -from .types.intent import CreateIntentRequest -from .types.intent import DeleteIntentRequest -from .types.intent import GetIntentRequest -from .types.intent import Intent -from .types.intent import ListIntentsRequest -from .types.intent import ListIntentsResponse -from .types.intent import UpdateIntentRequest -from .types.intent import IntentView -from .types.page import CreatePageRequest -from .types.page import DeletePageRequest -from .types.page import EventHandler -from .types.page import Form -from .types.page import GetPageRequest -from .types.page import ListPagesRequest -from .types.page import ListPagesResponse -from .types.page import Page -from .types.page import TransitionRoute -from .types.page import UpdatePageRequest -from .types.response_message import ResponseMessage -from .types.security_settings import CreateSecuritySettingsRequest -from .types.security_settings import DeleteSecuritySettingsRequest -from .types.security_settings import GetSecuritySettingsRequest -from .types.security_settings import ListSecuritySettingsRequest -from .types.security_settings import ListSecuritySettingsResponse -from .types.security_settings import SecuritySettings -from .types.security_settings import UpdateSecuritySettingsRequest -from .types.session import AudioInput -from .types.session import DetectIntentRequest -from .types.session import DetectIntentResponse -from .types.session import DtmfInput -from .types.session import EventInput -from .types.session import FulfillIntentRequest -from .types.session import FulfillIntentResponse -from .types.session import IntentInput -from .types.session import Match -from .types.session import MatchIntentRequest -from .types.session import MatchIntentResponse -from .types.session import QueryInput -from .types.session import QueryParameters -from .types.session import QueryResult -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.test_case import BatchDeleteTestCasesRequest -from .types.test_case import BatchRunTestCasesMetadata -from .types.test_case import BatchRunTestCasesRequest -from .types.test_case import BatchRunTestCasesResponse -from .types.test_case import CalculateCoverageRequest -from .types.test_case import CalculateCoverageResponse -from .types.test_case import ConversationTurn -from .types.test_case import CreateTestCaseRequest -from .types.test_case import ExportTestCasesMetadata -from .types.test_case import ExportTestCasesRequest -from .types.test_case import ExportTestCasesResponse -from .types.test_case import GetTestCaseRequest -from .types.test_case import GetTestCaseResultRequest -from .types.test_case import ImportTestCasesMetadata -from .types.test_case import ImportTestCasesRequest -from .types.test_case import ImportTestCasesResponse -from .types.test_case import IntentCoverage -from .types.test_case import ListTestCaseResultsRequest -from .types.test_case import ListTestCaseResultsResponse -from .types.test_case import ListTestCasesRequest -from .types.test_case import ListTestCasesResponse -from .types.test_case import RunTestCaseMetadata -from .types.test_case import RunTestCaseRequest -from .types.test_case import RunTestCaseResponse -from .types.test_case import TestCase -from .types.test_case import TestCaseError -from .types.test_case import TestCaseResult -from .types.test_case import TestConfig -from .types.test_case import TestError -from .types.test_case import TestRunDifference -from .types.test_case import TransitionCoverage -from .types.test_case import TransitionRouteGroupCoverage -from .types.test_case import UpdateTestCaseRequest -from .types.test_case import TestResult -from .types.transition_route_group import CreateTransitionRouteGroupRequest -from .types.transition_route_group import DeleteTransitionRouteGroupRequest -from .types.transition_route_group import GetTransitionRouteGroupRequest -from .types.transition_route_group import ListTransitionRouteGroupsRequest -from .types.transition_route_group import ListTransitionRouteGroupsResponse -from .types.transition_route_group import TransitionRouteGroup -from .types.transition_route_group import UpdateTransitionRouteGroupRequest -from .types.validation_message import ResourceName -from .types.validation_message import ValidationMessage -from .types.version import CreateVersionOperationMetadata -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 LoadVersionRequest -from .types.version import UpdateVersionRequest -from .types.version import Version -from .types.webhook import CreateWebhookRequest -from .types.webhook import DeleteWebhookRequest -from .types.webhook import GetWebhookRequest -from .types.webhook import ListWebhooksRequest -from .types.webhook import ListWebhooksResponse -from .types.webhook import PageInfo -from .types.webhook import SessionInfo -from .types.webhook import UpdateWebhookRequest -from .types.webhook import Webhook -from .types.webhook import WebhookRequest -from .types.webhook import WebhookResponse - -__all__ = ( - 'AgentsAsyncClient', - 'EntityTypesAsyncClient', - 'EnvironmentsAsyncClient', - 'ExperimentsAsyncClient', - 'FlowsAsyncClient', - 'IntentsAsyncClient', - 'PagesAsyncClient', - 'SecuritySettingsServiceAsyncClient', - 'SessionEntityTypesAsyncClient', - 'SessionsAsyncClient', - 'TestCasesAsyncClient', - 'TransitionRouteGroupsAsyncClient', - 'VersionsAsyncClient', - 'WebhooksAsyncClient', -'Agent', -'AgentValidationResult', -'AgentsClient', -'AudioEncoding', -'AudioInput', -'BatchDeleteTestCasesRequest', -'BatchRunTestCasesMetadata', -'BatchRunTestCasesRequest', -'BatchRunTestCasesResponse', -'CalculateCoverageRequest', -'CalculateCoverageResponse', -'ConversationTurn', -'CreateAgentRequest', -'CreateEntityTypeRequest', -'CreateEnvironmentRequest', -'CreateExperimentRequest', -'CreateFlowRequest', -'CreateIntentRequest', -'CreatePageRequest', -'CreateSecuritySettingsRequest', -'CreateSessionEntityTypeRequest', -'CreateTestCaseRequest', -'CreateTransitionRouteGroupRequest', -'CreateVersionOperationMetadata', -'CreateVersionRequest', -'CreateWebhookRequest', -'DeleteAgentRequest', -'DeleteEntityTypeRequest', -'DeleteEnvironmentRequest', -'DeleteExperimentRequest', -'DeleteFlowRequest', -'DeleteIntentRequest', -'DeletePageRequest', -'DeleteSecuritySettingsRequest', -'DeleteSessionEntityTypeRequest', -'DeleteTransitionRouteGroupRequest', -'DeleteVersionRequest', -'DeleteWebhookRequest', -'DetectIntentRequest', -'DetectIntentResponse', -'DtmfInput', -'EntityType', -'EntityTypesClient', -'Environment', -'EnvironmentsClient', -'EventHandler', -'EventInput', -'Experiment', -'ExperimentsClient', -'ExportAgentRequest', -'ExportAgentResponse', -'ExportFlowRequest', -'ExportFlowResponse', -'ExportTestCasesMetadata', -'ExportTestCasesRequest', -'ExportTestCasesResponse', -'Flow', -'FlowValidationResult', -'FlowsClient', -'Form', -'FulfillIntentRequest', -'FulfillIntentResponse', -'Fulfillment', -'GetAgentRequest', -'GetAgentValidationResultRequest', -'GetEntityTypeRequest', -'GetEnvironmentRequest', -'GetExperimentRequest', -'GetFlowRequest', -'GetFlowValidationResultRequest', -'GetIntentRequest', -'GetPageRequest', -'GetSecuritySettingsRequest', -'GetSessionEntityTypeRequest', -'GetTestCaseRequest', -'GetTestCaseResultRequest', -'GetTransitionRouteGroupRequest', -'GetVersionRequest', -'GetWebhookRequest', -'ImportFlowRequest', -'ImportFlowResponse', -'ImportTestCasesMetadata', -'ImportTestCasesRequest', -'ImportTestCasesResponse', -'InputAudioConfig', -'Intent', -'IntentCoverage', -'IntentInput', -'IntentView', -'IntentsClient', -'ListAgentsRequest', -'ListAgentsResponse', -'ListEntityTypesRequest', -'ListEntityTypesResponse', -'ListEnvironmentsRequest', -'ListEnvironmentsResponse', -'ListExperimentsRequest', -'ListExperimentsResponse', -'ListFlowsRequest', -'ListFlowsResponse', -'ListIntentsRequest', -'ListIntentsResponse', -'ListPagesRequest', -'ListPagesResponse', -'ListSecuritySettingsRequest', -'ListSecuritySettingsResponse', -'ListSessionEntityTypesRequest', -'ListSessionEntityTypesResponse', -'ListTestCaseResultsRequest', -'ListTestCaseResultsResponse', -'ListTestCasesRequest', -'ListTestCasesResponse', -'ListTransitionRouteGroupsRequest', -'ListTransitionRouteGroupsResponse', -'ListVersionsRequest', -'ListVersionsResponse', -'ListWebhooksRequest', -'ListWebhooksResponse', -'LoadVersionRequest', -'LookupEnvironmentHistoryRequest', -'LookupEnvironmentHistoryResponse', -'Match', -'MatchIntentRequest', -'MatchIntentResponse', -'NluSettings', -'OutputAudioConfig', -'OutputAudioEncoding', -'Page', -'PageInfo', -'PagesClient', -'QueryInput', -'QueryParameters', -'QueryResult', -'ResourceName', -'ResponseMessage', -'RestoreAgentRequest', -'RunTestCaseMetadata', -'RunTestCaseRequest', -'RunTestCaseResponse', -'SecuritySettings', -'SecuritySettingsServiceClient', -'SentimentAnalysisResult', -'SessionEntityType', -'SessionEntityTypesClient', -'SessionInfo', -'SessionsClient', -'SpeechModelVariant', -'SpeechToTextSettings', -'SpeechWordInfo', -'SsmlVoiceGender', -'StartExperimentRequest', -'StopExperimentRequest', -'StreamingDetectIntentRequest', -'StreamingDetectIntentResponse', -'StreamingRecognitionResult', -'SynthesizeSpeechConfig', -'TestCase', -'TestCaseError', -'TestCaseResult', -'TestCasesClient', -'TestConfig', -'TestError', -'TestResult', -'TestRunDifference', -'TextInput', -'TrainFlowRequest', -'TransitionCoverage', -'TransitionRoute', -'TransitionRouteGroup', -'TransitionRouteGroupCoverage', -'TransitionRouteGroupsClient', -'UpdateAgentRequest', -'UpdateEntityTypeRequest', -'UpdateEnvironmentRequest', -'UpdateExperimentRequest', -'UpdateFlowRequest', -'UpdateIntentRequest', -'UpdatePageRequest', -'UpdateSecuritySettingsRequest', -'UpdateSessionEntityTypeRequest', -'UpdateTestCaseRequest', -'UpdateTransitionRouteGroupRequest', -'UpdateVersionRequest', -'UpdateWebhookRequest', -'ValidateAgentRequest', -'ValidateFlowRequest', -'ValidationMessage', -'VariantsHistory', -'Version', -'VersionVariants', -'VersionsClient', -'VoiceSelectionParams', -'Webhook', -'WebhookRequest', -'WebhookResponse', -'WebhooksClient', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json deleted file mode 100644 index 6c6db5d4..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/gapic_metadata.json +++ /dev/null @@ -1,1095 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.dialogflowcx_v3", - "protoPackage": "google.cloud.dialogflow.cx.v3", - "schema": "1.0", - "services": { - "Agents": { - "clients": { - "grpc": { - "libraryClient": "AgentsClient", - "rpcs": { - "CreateAgent": { - "methods": [ - "create_agent" - ] - }, - "DeleteAgent": { - "methods": [ - "delete_agent" - ] - }, - "ExportAgent": { - "methods": [ - "export_agent" - ] - }, - "GetAgent": { - "methods": [ - "get_agent" - ] - }, - "GetAgentValidationResult": { - "methods": [ - "get_agent_validation_result" - ] - }, - "ListAgents": { - "methods": [ - "list_agents" - ] - }, - "RestoreAgent": { - "methods": [ - "restore_agent" - ] - }, - "UpdateAgent": { - "methods": [ - "update_agent" - ] - }, - "ValidateAgent": { - "methods": [ - "validate_agent" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AgentsAsyncClient", - "rpcs": { - "CreateAgent": { - "methods": [ - "create_agent" - ] - }, - "DeleteAgent": { - "methods": [ - "delete_agent" - ] - }, - "ExportAgent": { - "methods": [ - "export_agent" - ] - }, - "GetAgent": { - "methods": [ - "get_agent" - ] - }, - "GetAgentValidationResult": { - "methods": [ - "get_agent_validation_result" - ] - }, - "ListAgents": { - "methods": [ - "list_agents" - ] - }, - "RestoreAgent": { - "methods": [ - "restore_agent" - ] - }, - "UpdateAgent": { - "methods": [ - "update_agent" - ] - }, - "ValidateAgent": { - "methods": [ - "validate_agent" - ] - } - } - } - } - }, - "EntityTypes": { - "clients": { - "grpc": { - "libraryClient": "EntityTypesClient", - "rpcs": { - "CreateEntityType": { - "methods": [ - "create_entity_type" - ] - }, - "DeleteEntityType": { - "methods": [ - "delete_entity_type" - ] - }, - "GetEntityType": { - "methods": [ - "get_entity_type" - ] - }, - "ListEntityTypes": { - "methods": [ - "list_entity_types" - ] - }, - "UpdateEntityType": { - "methods": [ - "update_entity_type" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EntityTypesAsyncClient", - "rpcs": { - "CreateEntityType": { - "methods": [ - "create_entity_type" - ] - }, - "DeleteEntityType": { - "methods": [ - "delete_entity_type" - ] - }, - "GetEntityType": { - "methods": [ - "get_entity_type" - ] - }, - "ListEntityTypes": { - "methods": [ - "list_entity_types" - ] - }, - "UpdateEntityType": { - "methods": [ - "update_entity_type" - ] - } - } - } - } - }, - "Environments": { - "clients": { - "grpc": { - "libraryClient": "EnvironmentsClient", - "rpcs": { - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LookupEnvironmentHistory": { - "methods": [ - "lookup_environment_history" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EnvironmentsAsyncClient", - "rpcs": { - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LookupEnvironmentHistory": { - "methods": [ - "lookup_environment_history" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - } - } - }, - "Experiments": { - "clients": { - "grpc": { - "libraryClient": "ExperimentsClient", - "rpcs": { - "CreateExperiment": { - "methods": [ - "create_experiment" - ] - }, - "DeleteExperiment": { - "methods": [ - "delete_experiment" - ] - }, - "GetExperiment": { - "methods": [ - "get_experiment" - ] - }, - "ListExperiments": { - "methods": [ - "list_experiments" - ] - }, - "StartExperiment": { - "methods": [ - "start_experiment" - ] - }, - "StopExperiment": { - "methods": [ - "stop_experiment" - ] - }, - "UpdateExperiment": { - "methods": [ - "update_experiment" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ExperimentsAsyncClient", - "rpcs": { - "CreateExperiment": { - "methods": [ - "create_experiment" - ] - }, - "DeleteExperiment": { - "methods": [ - "delete_experiment" - ] - }, - "GetExperiment": { - "methods": [ - "get_experiment" - ] - }, - "ListExperiments": { - "methods": [ - "list_experiments" - ] - }, - "StartExperiment": { - "methods": [ - "start_experiment" - ] - }, - "StopExperiment": { - "methods": [ - "stop_experiment" - ] - }, - "UpdateExperiment": { - "methods": [ - "update_experiment" - ] - } - } - } - } - }, - "Flows": { - "clients": { - "grpc": { - "libraryClient": "FlowsClient", - "rpcs": { - "CreateFlow": { - "methods": [ - "create_flow" - ] - }, - "DeleteFlow": { - "methods": [ - "delete_flow" - ] - }, - "ExportFlow": { - "methods": [ - "export_flow" - ] - }, - "GetFlow": { - "methods": [ - "get_flow" - ] - }, - "GetFlowValidationResult": { - "methods": [ - "get_flow_validation_result" - ] - }, - "ImportFlow": { - "methods": [ - "import_flow" - ] - }, - "ListFlows": { - "methods": [ - "list_flows" - ] - }, - "TrainFlow": { - "methods": [ - "train_flow" - ] - }, - "UpdateFlow": { - "methods": [ - "update_flow" - ] - }, - "ValidateFlow": { - "methods": [ - "validate_flow" - ] - } - } - }, - "grpc-async": { - "libraryClient": "FlowsAsyncClient", - "rpcs": { - "CreateFlow": { - "methods": [ - "create_flow" - ] - }, - "DeleteFlow": { - "methods": [ - "delete_flow" - ] - }, - "ExportFlow": { - "methods": [ - "export_flow" - ] - }, - "GetFlow": { - "methods": [ - "get_flow" - ] - }, - "GetFlowValidationResult": { - "methods": [ - "get_flow_validation_result" - ] - }, - "ImportFlow": { - "methods": [ - "import_flow" - ] - }, - "ListFlows": { - "methods": [ - "list_flows" - ] - }, - "TrainFlow": { - "methods": [ - "train_flow" - ] - }, - "UpdateFlow": { - "methods": [ - "update_flow" - ] - }, - "ValidateFlow": { - "methods": [ - "validate_flow" - ] - } - } - } - } - }, - "Intents": { - "clients": { - "grpc": { - "libraryClient": "IntentsClient", - "rpcs": { - "CreateIntent": { - "methods": [ - "create_intent" - ] - }, - "DeleteIntent": { - "methods": [ - "delete_intent" - ] - }, - "GetIntent": { - "methods": [ - "get_intent" - ] - }, - "ListIntents": { - "methods": [ - "list_intents" - ] - }, - "UpdateIntent": { - "methods": [ - "update_intent" - ] - } - } - }, - "grpc-async": { - "libraryClient": "IntentsAsyncClient", - "rpcs": { - "CreateIntent": { - "methods": [ - "create_intent" - ] - }, - "DeleteIntent": { - "methods": [ - "delete_intent" - ] - }, - "GetIntent": { - "methods": [ - "get_intent" - ] - }, - "ListIntents": { - "methods": [ - "list_intents" - ] - }, - "UpdateIntent": { - "methods": [ - "update_intent" - ] - } - } - } - } - }, - "Pages": { - "clients": { - "grpc": { - "libraryClient": "PagesClient", - "rpcs": { - "CreatePage": { - "methods": [ - "create_page" - ] - }, - "DeletePage": { - "methods": [ - "delete_page" - ] - }, - "GetPage": { - "methods": [ - "get_page" - ] - }, - "ListPages": { - "methods": [ - "list_pages" - ] - }, - "UpdatePage": { - "methods": [ - "update_page" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PagesAsyncClient", - "rpcs": { - "CreatePage": { - "methods": [ - "create_page" - ] - }, - "DeletePage": { - "methods": [ - "delete_page" - ] - }, - "GetPage": { - "methods": [ - "get_page" - ] - }, - "ListPages": { - "methods": [ - "list_pages" - ] - }, - "UpdatePage": { - "methods": [ - "update_page" - ] - } - } - } - } - }, - "SecuritySettingsService": { - "clients": { - "grpc": { - "libraryClient": "SecuritySettingsServiceClient", - "rpcs": { - "CreateSecuritySettings": { - "methods": [ - "create_security_settings" - ] - }, - "DeleteSecuritySettings": { - "methods": [ - "delete_security_settings" - ] - }, - "GetSecuritySettings": { - "methods": [ - "get_security_settings" - ] - }, - "ListSecuritySettings": { - "methods": [ - "list_security_settings" - ] - }, - "UpdateSecuritySettings": { - "methods": [ - "update_security_settings" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecuritySettingsServiceAsyncClient", - "rpcs": { - "CreateSecuritySettings": { - "methods": [ - "create_security_settings" - ] - }, - "DeleteSecuritySettings": { - "methods": [ - "delete_security_settings" - ] - }, - "GetSecuritySettings": { - "methods": [ - "get_security_settings" - ] - }, - "ListSecuritySettings": { - "methods": [ - "list_security_settings" - ] - }, - "UpdateSecuritySettings": { - "methods": [ - "update_security_settings" - ] - } - } - } - } - }, - "SessionEntityTypes": { - "clients": { - "grpc": { - "libraryClient": "SessionEntityTypesClient", - "rpcs": { - "CreateSessionEntityType": { - "methods": [ - "create_session_entity_type" - ] - }, - "DeleteSessionEntityType": { - "methods": [ - "delete_session_entity_type" - ] - }, - "GetSessionEntityType": { - "methods": [ - "get_session_entity_type" - ] - }, - "ListSessionEntityTypes": { - "methods": [ - "list_session_entity_types" - ] - }, - "UpdateSessionEntityType": { - "methods": [ - "update_session_entity_type" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SessionEntityTypesAsyncClient", - "rpcs": { - "CreateSessionEntityType": { - "methods": [ - "create_session_entity_type" - ] - }, - "DeleteSessionEntityType": { - "methods": [ - "delete_session_entity_type" - ] - }, - "GetSessionEntityType": { - "methods": [ - "get_session_entity_type" - ] - }, - "ListSessionEntityTypes": { - "methods": [ - "list_session_entity_types" - ] - }, - "UpdateSessionEntityType": { - "methods": [ - "update_session_entity_type" - ] - } - } - } - } - }, - "Sessions": { - "clients": { - "grpc": { - "libraryClient": "SessionsClient", - "rpcs": { - "DetectIntent": { - "methods": [ - "detect_intent" - ] - }, - "FulfillIntent": { - "methods": [ - "fulfill_intent" - ] - }, - "MatchIntent": { - "methods": [ - "match_intent" - ] - }, - "StreamingDetectIntent": { - "methods": [ - "streaming_detect_intent" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SessionsAsyncClient", - "rpcs": { - "DetectIntent": { - "methods": [ - "detect_intent" - ] - }, - "FulfillIntent": { - "methods": [ - "fulfill_intent" - ] - }, - "MatchIntent": { - "methods": [ - "match_intent" - ] - }, - "StreamingDetectIntent": { - "methods": [ - "streaming_detect_intent" - ] - } - } - } - } - }, - "TestCases": { - "clients": { - "grpc": { - "libraryClient": "TestCasesClient", - "rpcs": { - "BatchDeleteTestCases": { - "methods": [ - "batch_delete_test_cases" - ] - }, - "BatchRunTestCases": { - "methods": [ - "batch_run_test_cases" - ] - }, - "CalculateCoverage": { - "methods": [ - "calculate_coverage" - ] - }, - "CreateTestCase": { - "methods": [ - "create_test_case" - ] - }, - "ExportTestCases": { - "methods": [ - "export_test_cases" - ] - }, - "GetTestCase": { - "methods": [ - "get_test_case" - ] - }, - "GetTestCaseResult": { - "methods": [ - "get_test_case_result" - ] - }, - "ImportTestCases": { - "methods": [ - "import_test_cases" - ] - }, - "ListTestCaseResults": { - "methods": [ - "list_test_case_results" - ] - }, - "ListTestCases": { - "methods": [ - "list_test_cases" - ] - }, - "RunTestCase": { - "methods": [ - "run_test_case" - ] - }, - "UpdateTestCase": { - "methods": [ - "update_test_case" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TestCasesAsyncClient", - "rpcs": { - "BatchDeleteTestCases": { - "methods": [ - "batch_delete_test_cases" - ] - }, - "BatchRunTestCases": { - "methods": [ - "batch_run_test_cases" - ] - }, - "CalculateCoverage": { - "methods": [ - "calculate_coverage" - ] - }, - "CreateTestCase": { - "methods": [ - "create_test_case" - ] - }, - "ExportTestCases": { - "methods": [ - "export_test_cases" - ] - }, - "GetTestCase": { - "methods": [ - "get_test_case" - ] - }, - "GetTestCaseResult": { - "methods": [ - "get_test_case_result" - ] - }, - "ImportTestCases": { - "methods": [ - "import_test_cases" - ] - }, - "ListTestCaseResults": { - "methods": [ - "list_test_case_results" - ] - }, - "ListTestCases": { - "methods": [ - "list_test_cases" - ] - }, - "RunTestCase": { - "methods": [ - "run_test_case" - ] - }, - "UpdateTestCase": { - "methods": [ - "update_test_case" - ] - } - } - } - } - }, - "TransitionRouteGroups": { - "clients": { - "grpc": { - "libraryClient": "TransitionRouteGroupsClient", - "rpcs": { - "CreateTransitionRouteGroup": { - "methods": [ - "create_transition_route_group" - ] - }, - "DeleteTransitionRouteGroup": { - "methods": [ - "delete_transition_route_group" - ] - }, - "GetTransitionRouteGroup": { - "methods": [ - "get_transition_route_group" - ] - }, - "ListTransitionRouteGroups": { - "methods": [ - "list_transition_route_groups" - ] - }, - "UpdateTransitionRouteGroup": { - "methods": [ - "update_transition_route_group" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TransitionRouteGroupsAsyncClient", - "rpcs": { - "CreateTransitionRouteGroup": { - "methods": [ - "create_transition_route_group" - ] - }, - "DeleteTransitionRouteGroup": { - "methods": [ - "delete_transition_route_group" - ] - }, - "GetTransitionRouteGroup": { - "methods": [ - "get_transition_route_group" - ] - }, - "ListTransitionRouteGroups": { - "methods": [ - "list_transition_route_groups" - ] - }, - "UpdateTransitionRouteGroup": { - "methods": [ - "update_transition_route_group" - ] - } - } - } - } - }, - "Versions": { - "clients": { - "grpc": { - "libraryClient": "VersionsClient", - "rpcs": { - "CreateVersion": { - "methods": [ - "create_version" - ] - }, - "DeleteVersion": { - "methods": [ - "delete_version" - ] - }, - "GetVersion": { - "methods": [ - "get_version" - ] - }, - "ListVersions": { - "methods": [ - "list_versions" - ] - }, - "LoadVersion": { - "methods": [ - "load_version" - ] - }, - "UpdateVersion": { - "methods": [ - "update_version" - ] - } - } - }, - "grpc-async": { - "libraryClient": "VersionsAsyncClient", - "rpcs": { - "CreateVersion": { - "methods": [ - "create_version" - ] - }, - "DeleteVersion": { - "methods": [ - "delete_version" - ] - }, - "GetVersion": { - "methods": [ - "get_version" - ] - }, - "ListVersions": { - "methods": [ - "list_versions" - ] - }, - "LoadVersion": { - "methods": [ - "load_version" - ] - }, - "UpdateVersion": { - "methods": [ - "update_version" - ] - } - } - } - } - }, - "Webhooks": { - "clients": { - "grpc": { - "libraryClient": "WebhooksClient", - "rpcs": { - "CreateWebhook": { - "methods": [ - "create_webhook" - ] - }, - "DeleteWebhook": { - "methods": [ - "delete_webhook" - ] - }, - "GetWebhook": { - "methods": [ - "get_webhook" - ] - }, - "ListWebhooks": { - "methods": [ - "list_webhooks" - ] - }, - "UpdateWebhook": { - "methods": [ - "update_webhook" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WebhooksAsyncClient", - "rpcs": { - "CreateWebhook": { - "methods": [ - "create_webhook" - ] - }, - "DeleteWebhook": { - "methods": [ - "delete_webhook" - ] - }, - "GetWebhook": { - "methods": [ - "get_webhook" - ] - }, - "ListWebhooks": { - "methods": [ - "list_webhooks" - ] - }, - "UpdateWebhook": { - "methods": [ - "update_webhook" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed deleted file mode 100644 index 60fdca49..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-dialogflowcx package uses inline types. diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v3/google/cloud/dialogflowcx_v3/services/agents/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/__init__.py deleted file mode 100644 index 057c8b80..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py deleted file mode 100644 index afcab083..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/async_client.py +++ /dev/null @@ -1,892 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.agents import pagers -from google.cloud.dialogflowcx_v3.types import agent -from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent -from google.cloud.dialogflowcx_v3.types import flow -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport -from .client import AgentsClient - - -class AgentsAsyncClient: - """Service for managing [Agents][google.cloud.dialogflow.cx.v3.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) - agent_validation_result_path = staticmethod(AgentsClient.agent_validation_result_path) - parse_agent_validation_result_path = staticmethod(AgentsClient.parse_agent_validation_result_path) - environment_path = staticmethod(AgentsClient.environment_path) - parse_environment_path = staticmethod(AgentsClient.parse_environment_path) - flow_path = staticmethod(AgentsClient.flow_path) - parse_flow_path = staticmethod(AgentsClient.parse_flow_path) - flow_validation_result_path = staticmethod(AgentsClient.flow_validation_result_path) - parse_flow_validation_result_path = staticmethod(AgentsClient.parse_flow_validation_result_path) - security_settings_path = staticmethod(AgentsClient.security_settings_path) - parse_security_settings_path = staticmethod(AgentsClient.parse_security_settings_path) - common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AgentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AgentsClient.common_folder_path) - parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) - common_organization_path = staticmethod(AgentsClient.common_organization_path) - parse_common_organization_path = staticmethod(AgentsClient.parse_common_organization_path) - common_project_path = staticmethod(AgentsClient.common_project_path) - parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) - common_location_path = staticmethod(AgentsClient.common_location_path) - parse_common_location_path = staticmethod(AgentsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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 list_agents(self, - request: agent.ListAgentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAgentsAsyncPager: - r"""Returns the list of all agents in the specified - location. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListAgentsRequest`): - The request object. The request message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. - parent (:class:`str`): - Required. The location to list all agents 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.dialogflowcx_v3.services.agents.pagers.ListAgentsAsyncPager: - The response message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. - - 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.ListAgentsRequest(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_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.ListAgentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_agent(self, - request: agent.GetAgentRequest = None, - *, - name: 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.dialogflowcx_v3.types.GetAgentRequest`): - The request object. The request message for - [Agents.GetAgent][google.cloud.dialogflow.cx.v3.Agents.GetAgent]. - name (:class:`str`): - Required. The name of the agent. Format: - ``projects//locations//agents/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3.EntityType], - [Flows][google.cloud.dialogflow.cx.v3.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = agent.GetAgentRequest(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_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(( - ("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_agent(self, - request: gcdc_agent.CreateAgentRequest = None, - *, - parent: str = None, - agent: gcdc_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_agent.Agent: - r"""Creates an agent in the specified location. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateAgentRequest`): - The request object. The request message for - [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent]. - parent (:class:`str`): - Required. The location to create a agent for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - agent (:class:`google.cloud.dialogflowcx_v3.types.Agent`): - Required. The agent to create. - 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.dialogflowcx_v3.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3.EntityType], - [Flows][google.cloud.dialogflow.cx.v3.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 = gcdc_agent.CreateAgentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if agent is not None: - 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.create_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 update_agent(self, - request: gcdc_agent.UpdateAgentRequest = None, - *, - agent: gcdc_agent.Agent = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_agent.Agent: - r"""Updates the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateAgentRequest`): - The request object. The request message for - [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent]. - agent (:class:`google.cloud.dialogflowcx_v3.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. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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.dialogflowcx_v3.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3.EntityType], - [Flows][google.cloud.dialogflow.cx.v3.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, 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 = gcdc_agent.UpdateAgentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if agent is not None: - request.agent = agent - if update_mask is not None: - 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_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.name", request.agent.name), - )), - ) - - # 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, - *, - name: 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.dialogflowcx_v3.types.DeleteAgentRequest`): - The request object. The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3.Agents.DeleteAgent]. - name (:class:`str`): - Required. The name of the agent to delete. Format: - ``projects//locations//agents/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = agent.DeleteAgentRequest(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_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(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def export_agent(self, - request: agent.ExportAgentRequest = 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 binary file. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ExportAgentRequest`): - The request object. The request message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.ExportAgentResponse` - The response message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. - - """ - # Create or coerce a protobuf request object. - request = agent.ExportAgentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_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(( - ("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, - agent.ExportAgentResponse, - 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 binary file. - Replaces the current agent with a new one. Note that all - existing resources in agent (e.g. intents, entity types, - flows) will be removed. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.RestoreAgentRequest`): - The request object. The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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(( - ("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=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def validate_agent(self, - request: agent.ValidateAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.AgentValidationResult: - r"""Validates the specified agent and creates or updates - validation results. The agent in draft version is - validated. Please call this API after the training is - completed to get the complete validation results. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ValidateAgentRequest`): - The request object. The request message for - [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3.Agents.ValidateAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.AgentValidationResult: - The response message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. - - """ - # Create or coerce a protobuf request object. - request = agent.ValidateAgentRequest(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.validate_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(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_agent_validation_result(self, - request: agent.GetAgentValidationResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.AgentValidationResult: - r"""Gets the latest agent validation result. Agent - validation is performed when ValidateAgent is called. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetAgentValidationResultRequest`): - The request object. The request message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. - name (:class:`str`): - Required. The agent name. Format: - ``projects//locations//agents//validationResult``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.AgentValidationResult: - The response message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = agent.GetAgentValidationResultRequest(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_agent_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(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AgentsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py deleted file mode 100644 index fb129509..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/client.py +++ /dev/null @@ -1,1127 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.agents import pagers -from google.cloud.dialogflowcx_v3.types import agent -from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent -from google.cloud.dialogflowcx_v3.types import flow -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AgentsGrpcTransport -from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport - - -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.cx.v3.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,location: str,agent: str,) -> str: - """Returns a fully-qualified agent string.""" - return "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) - - @staticmethod - def parse_agent_path(path: str) -> Dict[str,str]: - """Parses a agent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def agent_validation_result_path(project: str,location: str,agent: str,) -> str: - """Returns a fully-qualified agent_validation_result string.""" - return "projects/{project}/locations/{location}/agents/{agent}/validationResult".format(project=project, location=location, agent=agent, ) - - @staticmethod - def parse_agent_validation_result_path(path: str) -> Dict[str,str]: - """Parses a agent_validation_result path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/validationResult$", path) - return m.groupdict() if m else {} - - @staticmethod - def environment_path(project: str,location: str,agent: str,environment: str,) -> str: - """Returns a fully-qualified environment string.""" - return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - - @staticmethod - def parse_environment_path(path: str) -> Dict[str,str]: - """Parses a environment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_validation_result_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow_validation_result string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_validation_result_path(path: str) -> Dict[str,str]: - """Parses a flow_validation_result path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_settings_path(project: str,location: str,security_settings: str,) -> str: - """Returns a fully-qualified security_settings string.""" - return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - - @staticmethod - def parse_security_settings_path(path: str) -> Dict[str,str]: - """Parses a security_settings path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def 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 list_agents(self, - request: agent.ListAgentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAgentsPager: - r"""Returns the list of all agents in the specified - location. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListAgentsRequest): - The request object. The request message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. - parent (str): - Required. The location to list all agents 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.dialogflowcx_v3.services.agents.pagers.ListAgentsPager: - The response message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. - - 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.ListAgentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, agent.ListAgentsRequest): - request = agent.ListAgentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_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.ListAgentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_agent(self, - request: agent.GetAgentRequest = None, - *, - name: 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.dialogflowcx_v3.types.GetAgentRequest): - The request object. The request message for - [Agents.GetAgent][google.cloud.dialogflow.cx.v3.Agents.GetAgent]. - name (str): - Required. The name of the agent. Format: - ``projects//locations//agents/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3.EntityType], - [Flows][google.cloud.dialogflow.cx.v3.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 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 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_agent] - - # Certain fields should be provided 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_agent(self, - request: gcdc_agent.CreateAgentRequest = None, - *, - parent: str = None, - agent: gcdc_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_agent.Agent: - r"""Creates an agent in the specified location. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateAgentRequest): - The request object. The request message for - [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent]. - parent (str): - Required. The location to create a agent for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - agent (google.cloud.dialogflowcx_v3.types.Agent): - Required. The agent to create. - 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.dialogflowcx_v3.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3.EntityType], - [Flows][google.cloud.dialogflow.cx.v3.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 gcdc_agent.CreateAgentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_agent.CreateAgentRequest): - request = gcdc_agent.CreateAgentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if agent is not None: - request.agent = agent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_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 update_agent(self, - request: gcdc_agent.UpdateAgentRequest = None, - *, - agent: gcdc_agent.Agent = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_agent.Agent: - r"""Updates the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateAgentRequest): - The request object. The request message for - [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent]. - agent (google.cloud.dialogflowcx_v3.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. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.dialogflowcx_v3.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3.EntityType], - [Flows][google.cloud.dialogflow.cx.v3.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, 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 gcdc_agent.UpdateAgentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_agent.UpdateAgentRequest): - request = gcdc_agent.UpdateAgentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if agent is not None: - request.agent = agent - if update_mask is not None: - 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_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("agent.name", request.agent.name), - )), - ) - - # 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, - *, - name: 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.dialogflowcx_v3.types.DeleteAgentRequest): - The request object. The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3.Agents.DeleteAgent]. - name (str): - Required. The name of the agent to delete. Format: - ``projects//locations//agents/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 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 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_agent] - - # Certain fields should be 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 export_agent(self, - request: agent.ExportAgentRequest = 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 binary file. - - Args: - request (google.cloud.dialogflowcx_v3.types.ExportAgentRequest): - The request object. The request message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.ExportAgentResponse` - The response message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a agent.ExportAgentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, agent.ExportAgentRequest): - request = agent.ExportAgentRequest(request) - - # 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(( - ("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, - agent.ExportAgentResponse, - 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 binary file. - Replaces the current agent with a new one. Note that all - existing resources in agent (e.g. intents, entity types, - flows) will be removed. - - Args: - request (google.cloud.dialogflowcx_v3.types.RestoreAgentRequest): - The request object. The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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(( - ("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=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def validate_agent(self, - request: agent.ValidateAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.AgentValidationResult: - r"""Validates the specified agent and creates or updates - validation results. The agent in draft version is - validated. Please call this API after the training is - completed to get the complete validation results. - - Args: - request (google.cloud.dialogflowcx_v3.types.ValidateAgentRequest): - The request object. The request message for - [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3.Agents.ValidateAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.AgentValidationResult: - The response message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a agent.ValidateAgentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, agent.ValidateAgentRequest): - request = agent.ValidateAgentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_agent_validation_result(self, - request: agent.GetAgentValidationResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.AgentValidationResult: - r"""Gets the latest agent validation result. Agent - validation is performed when ValidateAgent is called. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetAgentValidationResultRequest): - The request object. The request message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. - name (str): - Required. The agent name. Format: - ``projects//locations//agents//validationResult``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.AgentValidationResult: - The response message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 agent.GetAgentValidationResultRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, agent.GetAgentValidationResultRequest): - request = agent.GetAgentValidationResultRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_agent_validation_result] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AgentsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/pagers.py deleted file mode 100644 index 9a1a5e7d..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import agent - - -class ListAgentsPager: - """A pager for iterating through ``list_agents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``agents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAgents`` requests and continue to iterate - through the ``agents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` - 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.ListAgentsResponse], - request: agent.ListAgentsRequest, - response: agent.ListAgentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListAgentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListAgentsResponse): - 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.ListAgentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[agent.ListAgentsResponse]: - 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 ListAgentsAsyncPager: - """A pager for iterating through ``list_agents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``agents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAgents`` requests and continue to iterate - through the ``agents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListAgentsResponse` - 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.ListAgentsResponse]], - request: agent.ListAgentsRequest, - response: agent.ListAgentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListAgentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListAgentsResponse): - 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.ListAgentsRequest(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.ListAgentsResponse]: - 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/v3/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py deleted file mode 100644 index 0dc0c06c..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.py deleted file mode 100644 index a776e295..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/base.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 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.dialogflowcx_v3.types import agent -from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent -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-dialogflowcx', - ).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.list_agents: gapic_v1.method.wrap_method( - self.list_agents, - default_timeout=None, - client_info=client_info, - ), - self.get_agent: gapic_v1.method.wrap_method( - self.get_agent, - default_timeout=None, - client_info=client_info, - ), - self.create_agent: gapic_v1.method.wrap_method( - self.create_agent, - default_timeout=None, - client_info=client_info, - ), - self.update_agent: gapic_v1.method.wrap_method( - self.update_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.export_agent: gapic_v1.method.wrap_method( - self.export_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.validate_agent: gapic_v1.method.wrap_method( - self.validate_agent, - default_timeout=None, - client_info=client_info, - ), - self.get_agent_validation_result: gapic_v1.method.wrap_method( - self.get_agent_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 list_agents(self) -> Callable[ - [agent.ListAgentsRequest], - Union[ - agent.ListAgentsResponse, - Awaitable[agent.ListAgentsResponse] - ]]: - raise NotImplementedError() - - @property - def get_agent(self) -> Callable[ - [agent.GetAgentRequest], - Union[ - agent.Agent, - Awaitable[agent.Agent] - ]]: - raise NotImplementedError() - - @property - def create_agent(self) -> Callable[ - [gcdc_agent.CreateAgentRequest], - Union[ - gcdc_agent.Agent, - Awaitable[gcdc_agent.Agent] - ]]: - raise NotImplementedError() - - @property - def update_agent(self) -> Callable[ - [gcdc_agent.UpdateAgentRequest], - Union[ - gcdc_agent.Agent, - Awaitable[gcdc_agent.Agent] - ]]: - raise NotImplementedError() - - @property - def delete_agent(self) -> Callable[ - [agent.DeleteAgentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def export_agent(self) -> Callable[ - [agent.ExportAgentRequest], - 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 validate_agent(self) -> Callable[ - [agent.ValidateAgentRequest], - Union[ - agent.AgentValidationResult, - Awaitable[agent.AgentValidationResult] - ]]: - raise NotImplementedError() - - @property - def get_agent_validation_result(self) -> Callable[ - [agent.GetAgentValidationResultRequest], - Union[ - agent.AgentValidationResult, - Awaitable[agent.AgentValidationResult] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'AgentsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py deleted file mode 100644 index 21689209..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py +++ /dev/null @@ -1,485 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import agent -from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent -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.cx.v3.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 list_agents(self) -> Callable[ - [agent.ListAgentsRequest], - agent.ListAgentsResponse]: - r"""Return a callable for the list agents method over gRPC. - - Returns the list of all agents in the specified - location. - - Returns: - Callable[[~.ListAgentsRequest], - ~.ListAgentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_agents' not in self._stubs: - self._stubs['list_agents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Agents/ListAgents', - request_serializer=agent.ListAgentsRequest.serialize, - response_deserializer=agent.ListAgentsResponse.deserialize, - ) - return self._stubs['list_agents'] - - @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.cx.v3.Agents/GetAgent', - request_serializer=agent.GetAgentRequest.serialize, - response_deserializer=agent.Agent.deserialize, - ) - return self._stubs['get_agent'] - - @property - def create_agent(self) -> Callable[ - [gcdc_agent.CreateAgentRequest], - gcdc_agent.Agent]: - r"""Return a callable for the create agent method over gRPC. - - Creates an agent in the specified location. - - Returns: - Callable[[~.CreateAgentRequest], - ~.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 'create_agent' not in self._stubs: - self._stubs['create_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Agents/CreateAgent', - request_serializer=gcdc_agent.CreateAgentRequest.serialize, - response_deserializer=gcdc_agent.Agent.deserialize, - ) - return self._stubs['create_agent'] - - @property - def update_agent(self) -> Callable[ - [gcdc_agent.UpdateAgentRequest], - gcdc_agent.Agent]: - r"""Return a callable for the update agent method over gRPC. - - Updates the specified agent. - - Returns: - Callable[[~.UpdateAgentRequest], - ~.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 'update_agent' not in self._stubs: - self._stubs['update_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Agents/UpdateAgent', - request_serializer=gcdc_agent.UpdateAgentRequest.serialize, - response_deserializer=gcdc_agent.Agent.deserialize, - ) - return self._stubs['update_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.cx.v3.Agents/DeleteAgent', - request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_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 binary file. - - 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.cx.v3.Agents/ExportAgent', - request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_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 binary file. - Replaces the current agent with a new one. Note that all - existing resources in agent (e.g. intents, entity types, - flows) will be removed. - - 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.cx.v3.Agents/RestoreAgent', - request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['restore_agent'] - - @property - def validate_agent(self) -> Callable[ - [agent.ValidateAgentRequest], - agent.AgentValidationResult]: - r"""Return a callable for the validate agent method over gRPC. - - Validates the specified agent and creates or updates - validation results. The agent in draft version is - validated. Please call this API after the training is - completed to get the complete validation results. - - Returns: - Callable[[~.ValidateAgentRequest], - ~.AgentValidationResult]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_agent' not in self._stubs: - self._stubs['validate_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Agents/ValidateAgent', - request_serializer=agent.ValidateAgentRequest.serialize, - response_deserializer=agent.AgentValidationResult.deserialize, - ) - return self._stubs['validate_agent'] - - @property - def get_agent_validation_result(self) -> Callable[ - [agent.GetAgentValidationResultRequest], - agent.AgentValidationResult]: - r"""Return a callable for the get agent validation result method over gRPC. - - Gets the latest agent validation result. Agent - validation is performed when ValidateAgent is called. - - Returns: - Callable[[~.GetAgentValidationResultRequest], - ~.AgentValidationResult]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_validation_result' not in self._stubs: - self._stubs['get_agent_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Agents/GetAgentValidationResult', - request_serializer=agent.GetAgentValidationResultRequest.serialize, - response_deserializer=agent.AgentValidationResult.deserialize, - ) - return self._stubs['get_agent_validation_result'] - - -__all__ = ( - 'AgentsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py deleted file mode 100644 index 3b3ac651..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py +++ /dev/null @@ -1,489 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import agent -from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent -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.cx.v3.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 list_agents(self) -> Callable[ - [agent.ListAgentsRequest], - Awaitable[agent.ListAgentsResponse]]: - r"""Return a callable for the list agents method over gRPC. - - Returns the list of all agents in the specified - location. - - Returns: - Callable[[~.ListAgentsRequest], - Awaitable[~.ListAgentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_agents' not in self._stubs: - self._stubs['list_agents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Agents/ListAgents', - request_serializer=agent.ListAgentsRequest.serialize, - response_deserializer=agent.ListAgentsResponse.deserialize, - ) - return self._stubs['list_agents'] - - @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.cx.v3.Agents/GetAgent', - request_serializer=agent.GetAgentRequest.serialize, - response_deserializer=agent.Agent.deserialize, - ) - return self._stubs['get_agent'] - - @property - def create_agent(self) -> Callable[ - [gcdc_agent.CreateAgentRequest], - Awaitable[gcdc_agent.Agent]]: - r"""Return a callable for the create agent method over gRPC. - - Creates an agent in the specified location. - - Returns: - Callable[[~.CreateAgentRequest], - 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 'create_agent' not in self._stubs: - self._stubs['create_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Agents/CreateAgent', - request_serializer=gcdc_agent.CreateAgentRequest.serialize, - response_deserializer=gcdc_agent.Agent.deserialize, - ) - return self._stubs['create_agent'] - - @property - def update_agent(self) -> Callable[ - [gcdc_agent.UpdateAgentRequest], - Awaitable[gcdc_agent.Agent]]: - r"""Return a callable for the update agent method over gRPC. - - Updates the specified agent. - - Returns: - Callable[[~.UpdateAgentRequest], - 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 'update_agent' not in self._stubs: - self._stubs['update_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Agents/UpdateAgent', - request_serializer=gcdc_agent.UpdateAgentRequest.serialize, - response_deserializer=gcdc_agent.Agent.deserialize, - ) - return self._stubs['update_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.cx.v3.Agents/DeleteAgent', - request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_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 binary file. - - 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.cx.v3.Agents/ExportAgent', - request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_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 binary file. - Replaces the current agent with a new one. Note that all - existing resources in agent (e.g. intents, entity types, - flows) will be removed. - - 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.cx.v3.Agents/RestoreAgent', - request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['restore_agent'] - - @property - def validate_agent(self) -> Callable[ - [agent.ValidateAgentRequest], - Awaitable[agent.AgentValidationResult]]: - r"""Return a callable for the validate agent method over gRPC. - - Validates the specified agent and creates or updates - validation results. The agent in draft version is - validated. Please call this API after the training is - completed to get the complete validation results. - - Returns: - Callable[[~.ValidateAgentRequest], - Awaitable[~.AgentValidationResult]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_agent' not in self._stubs: - self._stubs['validate_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Agents/ValidateAgent', - request_serializer=agent.ValidateAgentRequest.serialize, - response_deserializer=agent.AgentValidationResult.deserialize, - ) - return self._stubs['validate_agent'] - - @property - def get_agent_validation_result(self) -> Callable[ - [agent.GetAgentValidationResultRequest], - Awaitable[agent.AgentValidationResult]]: - r"""Return a callable for the get agent validation result method over gRPC. - - Gets the latest agent validation result. Agent - validation is performed when ValidateAgent is called. - - Returns: - Callable[[~.GetAgentValidationResultRequest], - Awaitable[~.AgentValidationResult]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_validation_result' not in self._stubs: - self._stubs['get_agent_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Agents/GetAgentValidationResult', - request_serializer=agent.GetAgentValidationResultRequest.serialize, - response_deserializer=agent.AgentValidationResult.deserialize, - ) - return self._stubs['get_agent_validation_result'] - - -__all__ = ( - 'AgentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py deleted file mode 100644 index 82dfe86f..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py deleted file mode 100644 index b032bc8d..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py +++ /dev/null @@ -1,659 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.entity_types import pagers -from google.cloud.dialogflowcx_v3.types import entity_type -from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type -from google.protobuf import field_mask_pb2 # 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.cx.v3.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, - 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.dialogflowcx_v3.types.ListEntityTypesRequest`): - The request object. The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. - parent (:class:`str`): - Required. The agent to list all entity types for. - Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.entity_types.pagers.ListEntityTypesAsyncPager: - The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.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]) - if request is not 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 - - # 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, - 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.dialogflowcx_v3.types.GetEntityTypeRequest`): - The request object. The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.GetEntityType]. - name (:class:`str`): - Required. The name of the entity type. Format: - ``projects//locations//agents//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. - - Returns: - google.cloud.dialogflowcx_v3.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not 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 - - # 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: gcdc_entity_type.CreateEntityTypeRequest = None, - *, - parent: str = None, - entity_type: gcdc_entity_type.EntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateEntityTypeRequest`): - The request object. The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.CreateEntityType]. - parent (:class:`str`): - Required. The agent to create a entity type for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_type (:class:`google.cloud.dialogflowcx_v3.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. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_entity_type.CreateEntityTypeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entity_type is not None: - request.entity_type = 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_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: gcdc_entity_type.UpdateEntityTypeRequest = None, - *, - entity_type: gcdc_entity_type.EntityType = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_entity_type.EntityType: - r"""Updates the specified entity type. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateEntityTypeRequest`): - The request object. The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. - entity_type (:class:`google.cloud.dialogflowcx_v3.types.EntityType`): - 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. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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.dialogflowcx_v3.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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, 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 = gcdc_entity_type.UpdateEntityTypeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entity_type is not None: - request.entity_type = entity_type - if update_mask is not None: - 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.dialogflowcx_v3.types.DeleteEntityTypeRequest`): - The request object. The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.DeleteEntityType]. - name (:class:`str`): - Required. The name of the entity type to delete. Format: - ``projects//locations//agents//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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "EntityTypesAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py deleted file mode 100644 index 2570459d..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/client.py +++ /dev/null @@ -1,846 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.entity_types import pagers -from google.cloud.dialogflowcx_v3.types import entity_type -from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type -from google.protobuf import field_mask_pb2 # 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.cx.v3.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,location: str,agent: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?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, 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, - 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.dialogflowcx_v3.types.ListEntityTypesRequest): - The request object. The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. - parent (str): - Required. The agent to list all entity types for. - Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.entity_types.pagers.ListEntityTypesPager: - The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is 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 - - # 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, - 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.dialogflowcx_v3.types.GetEntityTypeRequest): - The request object. The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.GetEntityType]. - name (str): - Required. The name of the entity type. Format: - ``projects//locations//agents//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. - - Returns: - google.cloud.dialogflowcx_v3.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is 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 - - # 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: gcdc_entity_type.CreateEntityTypeRequest = None, - *, - parent: str = None, - entity_type: gcdc_entity_type.EntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateEntityTypeRequest): - The request object. The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.CreateEntityType]. - parent (str): - Required. The agent to create a entity type for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_type (google.cloud.dialogflowcx_v3.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. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_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, gcdc_entity_type.CreateEntityTypeRequest): - request = gcdc_entity_type.CreateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entity_type is not None: - request.entity_type = entity_type - - # 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: gcdc_entity_type.UpdateEntityTypeRequest = None, - *, - entity_type: gcdc_entity_type.EntityType = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_entity_type.EntityType: - r"""Updates the specified entity type. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateEntityTypeRequest): - The request object. The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. - entity_type (google.cloud.dialogflowcx_v3.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. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.dialogflowcx_v3.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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, 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 gcdc_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, gcdc_entity_type.UpdateEntityTypeRequest): - request = gcdc_entity_type.UpdateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entity_type is not None: - request.entity_type = entity_type - if update_mask is not None: - 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.dialogflowcx_v3.types.DeleteEntityTypeRequest): - The request object. The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.DeleteEntityType]. - name (str): - Required. The name of the entity type to delete. Format: - ``projects//locations//agents//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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "EntityTypesClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py deleted file mode 100644 index 6b479cd6..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import entity_type - - -class ListEntityTypesPager: - """A pager for iterating through ``list_entity_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.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/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py deleted file mode 100644 index 1a2aa82d..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py deleted file mode 100644 index f6eb1fb8..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/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.dialogflowcx_v3.types import entity_type -from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflowcx', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -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, - ), - } - - @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[ - [gcdc_entity_type.CreateEntityTypeRequest], - Union[ - gcdc_entity_type.EntityType, - Awaitable[gcdc_entity_type.EntityType] - ]]: - raise NotImplementedError() - - @property - def update_entity_type(self) -> Callable[ - [gcdc_entity_type.UpdateEntityTypeRequest], - Union[ - gcdc_entity_type.EntityType, - Awaitable[gcdc_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() - - -__all__ = ( - 'EntityTypesTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py deleted file mode 100644 index 32aea14e..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/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.dialogflowcx_v3.types import entity_type -from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 # type: ignore -from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO - - -class EntityTypesGrpcTransport(EntityTypesTransport): - """gRPC backend transport for EntityTypes. - - Service for managing - [EntityTypes][google.cloud.dialogflow.cx.v3.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] = {} - - 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_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.cx.v3.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.cx.v3.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[ - [gcdc_entity_type.CreateEntityTypeRequest], - gcdc_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.cx.v3.EntityTypes/CreateEntityType', - request_serializer=gcdc_entity_type.CreateEntityTypeRequest.serialize, - response_deserializer=gcdc_entity_type.EntityType.deserialize, - ) - return self._stubs['create_entity_type'] - - @property - def update_entity_type(self) -> Callable[ - [gcdc_entity_type.UpdateEntityTypeRequest], - gcdc_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.cx.v3.EntityTypes/UpdateEntityType', - request_serializer=gcdc_entity_type.UpdateEntityTypeRequest.serialize, - response_deserializer=gcdc_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.cx.v3.EntityTypes/DeleteEntityType', - request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entity_type'] - - -__all__ = ( - 'EntityTypesGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc_asyncio.py deleted file mode 100644 index 1ae72cb2..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/entity_types/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.dialogflowcx_v3.types import entity_type -from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 # 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.cx.v3.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] = {} - - 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_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.cx.v3.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.cx.v3.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[ - [gcdc_entity_type.CreateEntityTypeRequest], - Awaitable[gcdc_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.cx.v3.EntityTypes/CreateEntityType', - request_serializer=gcdc_entity_type.CreateEntityTypeRequest.serialize, - response_deserializer=gcdc_entity_type.EntityType.deserialize, - ) - return self._stubs['create_entity_type'] - - @property - def update_entity_type(self) -> Callable[ - [gcdc_entity_type.UpdateEntityTypeRequest], - Awaitable[gcdc_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.cx.v3.EntityTypes/UpdateEntityType', - request_serializer=gcdc_entity_type.UpdateEntityTypeRequest.serialize, - response_deserializer=gcdc_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.cx.v3.EntityTypes/DeleteEntityType', - request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entity_type'] - - -__all__ = ( - 'EntityTypesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/__init__.py deleted file mode 100644 index a3ad29ec..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py deleted file mode 100644 index 54621b60..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/async_client.py +++ /dev/null @@ -1,723 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.environments import pagers -from google.cloud.dialogflowcx_v3.types import environment -from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .client import EnvironmentsClient - - -class EnvironmentsAsyncClient: - """Service for managing - [Environments][google.cloud.dialogflow.cx.v3.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) - version_path = staticmethod(EnvironmentsClient.version_path) - parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) - common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) - parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) - common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) - parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) - common_project_path = staticmethod(EnvironmentsClient.common_project_path) - parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) - common_location_path = staticmethod(EnvironmentsClient.common_location_path) - parse_common_location_path = staticmethod(EnvironmentsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @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 environments in the specified - [Agent][google.cloud.dialogflow.cx.v3.Agent]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListEnvironmentsRequest`): - The request object. The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. - parent (:class:`str`): - Required. The - [Agent][google.cloud.dialogflow.cx.v3.Agent] to list all - environments for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.environments.pagers.ListEnvironmentsAsyncPager: - The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.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, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetEnvironmentRequest`): - The request object. The request message for - [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3.Environments.GetEnvironment]. - name (:class:`str`): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Environment: - Represents an environment for an - agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = environment.GetEnvironmentRequest(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_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: gcdc_environment.CreateEnvironmentRequest = None, - *, - parent: str = None, - environment: gcdc_environment.Environment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates an - [Environment][google.cloud.dialogflow.cx.v3.Environment] in the - specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateEnvironmentRequest`): - The request object. The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3.Environments.CreateEnvironment]. - parent (:class:`str`): - Required. The - [Agent][google.cloud.dialogflow.cx.v3.Agent] to create - an - [Environment][google.cloud.dialogflow.cx.v3.Environment] - for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (:class:`google.cloud.dialogflowcx_v3.types.Environment`): - Required. The environment to create. - This corresponds to the ``environment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, environment]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_environment.CreateEnvironmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if environment is not None: - request.environment = environment - - # 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcdc_environment.Environment, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def update_environment(self, - request: gcdc_environment.UpdateEnvironmentRequest = None, - *, - environment: gcdc_environment.Environment = 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 - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateEnvironmentRequest`): - The request object. The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3.Environments.UpdateEnvironment]. - environment (:class:`google.cloud.dialogflowcx_v3.types.Environment`): - Required. The environment to update. - This corresponds to the ``environment`` 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([environment, 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 = gcdc_environment.UpdateEnvironmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if environment is not None: - request.environment = environment - if update_mask is not None: - 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_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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcdc_environment.Environment, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def delete_environment(self, - request: environment.DeleteEnvironmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteEnvironmentRequest`): - The request object. The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3.Environments.DeleteEnvironment]. - name (:class:`str`): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment] - to delete. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = environment.DeleteEnvironmentRequest(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_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 lookup_environment_history(self, - request: environment.LookupEnvironmentHistoryRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.LookupEnvironmentHistoryAsyncPager: - r"""Looks up the history of the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest`): - The request object. The request message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. - name (:class:`str`): - Required. Resource name of the environment to look up - the history for. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.environments.pagers.LookupEnvironmentHistoryAsyncPager: - The response message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. - - 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([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 = environment.LookupEnvironmentHistoryRequest(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.lookup_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(( - ("name", request.name), - )), - ) - - # 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.LookupEnvironmentHistoryAsyncPager( - 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "EnvironmentsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py deleted file mode 100644 index 3a42717f..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/client.py +++ /dev/null @@ -1,919 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.environments import pagers -from google.cloud.dialogflowcx_v3.types import environment -from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EnvironmentsGrpcTransport -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport - - -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.cx.v3.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,location: str,agent: str,environment: str,) -> str: - """Returns a fully-qualified environment string.""" - return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - - @staticmethod - def parse_environment_path(path: str) -> Dict[str,str]: - """Parses a environment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: - """Returns a fully-qualified version string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - - @staticmethod - def parse_version_path(path: str) -> Dict[str,str]: - """Parses a version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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, 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 environments in the specified - [Agent][google.cloud.dialogflow.cx.v3.Agent]. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListEnvironmentsRequest): - The request object. The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. - parent (str): - Required. The - [Agent][google.cloud.dialogflow.cx.v3.Agent] to list all - environments for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.environments.pagers.ListEnvironmentsPager: - The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.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, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetEnvironmentRequest): - The request object. The request message for - [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3.Environments.GetEnvironment]. - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Environment: - Represents an environment for an - agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 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) - # 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_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: gcdc_environment.CreateEnvironmentRequest = None, - *, - parent: str = None, - environment: gcdc_environment.Environment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates an - [Environment][google.cloud.dialogflow.cx.v3.Environment] in the - specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateEnvironmentRequest): - The request object. The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3.Environments.CreateEnvironment]. - parent (str): - Required. The - [Agent][google.cloud.dialogflow.cx.v3.Agent] to create - an - [Environment][google.cloud.dialogflow.cx.v3.Environment] - for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (google.cloud.dialogflowcx_v3.types.Environment): - Required. The environment to create. - This corresponds to the ``environment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, environment]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_environment.CreateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_environment.CreateEnvironmentRequest): - request = gcdc_environment.CreateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if environment is not None: - request.environment = environment - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcdc_environment.Environment, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def update_environment(self, - request: gcdc_environment.UpdateEnvironmentRequest = None, - *, - environment: gcdc_environment.Environment = 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 - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateEnvironmentRequest): - The request object. The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3.Environments.UpdateEnvironment]. - environment (google.cloud.dialogflowcx_v3.types.Environment): - Required. The environment to update. - This corresponds to the ``environment`` 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflowcx_v3.types.Environment` Represents an environment for an agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([environment, 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 gcdc_environment.UpdateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_environment.UpdateEnvironmentRequest): - request = gcdc_environment.UpdateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if environment is not None: - request.environment = environment - if update_mask is not None: - 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_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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcdc_environment.Environment, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def delete_environment(self, - request: environment.DeleteEnvironmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3.types.DeleteEnvironmentRequest): - The request object. The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3.Environments.DeleteEnvironment]. - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment] - to delete. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 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) - # 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_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 lookup_environment_history(self, - request: environment.LookupEnvironmentHistoryRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.LookupEnvironmentHistoryPager: - r"""Looks up the history of the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest): - The request object. The request message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. - name (str): - Required. Resource name of the environment to look up - the history for. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.environments.pagers.LookupEnvironmentHistoryPager: - The response message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. - - 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([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 environment.LookupEnvironmentHistoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.LookupEnvironmentHistoryRequest): - request = environment.LookupEnvironmentHistoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.lookup_environment_history] - - # Certain fields should be provided 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.LookupEnvironmentHistoryPager( - 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "EnvironmentsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/pagers.py deleted file mode 100644 index 2f79748a..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import environment - - -class ListEnvironmentsPager: - """A pager for iterating through ``list_environments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.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 LookupEnvironmentHistoryPager: - """A pager for iterating through ``lookup_environment_history`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` object, and - provides an ``__iter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``LookupEnvironmentHistory`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` - 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.LookupEnvironmentHistoryResponse], - request: environment.LookupEnvironmentHistoryRequest, - response: environment.LookupEnvironmentHistoryResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse): - 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.LookupEnvironmentHistoryRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[environment.LookupEnvironmentHistoryResponse]: - 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 LookupEnvironmentHistoryAsyncPager: - """A pager for iterating through ``lookup_environment_history`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``LookupEnvironmentHistory`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse` - 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.LookupEnvironmentHistoryResponse]], - request: environment.LookupEnvironmentHistoryRequest, - response: environment.LookupEnvironmentHistoryResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.LookupEnvironmentHistoryResponse): - 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.LookupEnvironmentHistoryRequest(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.LookupEnvironmentHistoryResponse]: - 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) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py deleted file mode 100644 index fac90efe..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.py deleted file mode 100644 index e84ea41d..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/base.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. -# -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.dialogflowcx_v3.types import environment -from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment -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-dialogflowcx', - ).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.lookup_environment_history: gapic_v1.method.wrap_method( - self.lookup_environment_history, - 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_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[ - [gcdc_environment.CreateEnvironmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_environment(self) -> Callable[ - [gcdc_environment.UpdateEnvironmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_environment(self) -> Callable[ - [environment.DeleteEnvironmentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def lookup_environment_history(self) -> Callable[ - [environment.LookupEnvironmentHistoryRequest], - Union[ - environment.LookupEnvironmentHistoryResponse, - Awaitable[environment.LookupEnvironmentHistoryResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'EnvironmentsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py deleted file mode 100644 index 85af1ac2..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py +++ /dev/null @@ -1,407 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import environment -from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment -from google.longrunning import operations_pb2 # type: ignore -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.cx.v3.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] = {} - 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_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - environment.ListEnvironmentsResponse]: - r"""Return a callable for the list environments method over gRPC. - - Returns the list of all environments in the specified - [Agent][google.cloud.dialogflow.cx.v3.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.cx.v3.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 - [Environment][google.cloud.dialogflow.cx.v3.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.cx.v3.Environments/GetEnvironment', - request_serializer=environment.GetEnvironmentRequest.serialize, - response_deserializer=environment.Environment.deserialize, - ) - return self._stubs['get_environment'] - - @property - def create_environment(self) -> Callable[ - [gcdc_environment.CreateEnvironmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the create environment method over gRPC. - - Creates an - [Environment][google.cloud.dialogflow.cx.v3.Environment] in the - specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. - - Returns: - Callable[[~.CreateEnvironmentRequest], - ~.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_environment' not in self._stubs: - self._stubs['create_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Environments/CreateEnvironment', - request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_environment'] - - @property - def update_environment(self) -> Callable[ - [gcdc_environment.UpdateEnvironmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the update environment method over gRPC. - - Updates the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Returns: - Callable[[~.UpdateEnvironmentRequest], - ~.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_environment' not in self._stubs: - self._stubs['update_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Environments/UpdateEnvironment', - request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - 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 - [Environment][google.cloud.dialogflow.cx.v3.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.cx.v3.Environments/DeleteEnvironment', - request_serializer=environment.DeleteEnvironmentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_environment'] - - @property - def lookup_environment_history(self) -> Callable[ - [environment.LookupEnvironmentHistoryRequest], - environment.LookupEnvironmentHistoryResponse]: - r"""Return a callable for the lookup environment history method over gRPC. - - Looks up the history of the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Returns: - Callable[[~.LookupEnvironmentHistoryRequest], - ~.LookupEnvironmentHistoryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'lookup_environment_history' not in self._stubs: - self._stubs['lookup_environment_history'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Environments/LookupEnvironmentHistory', - request_serializer=environment.LookupEnvironmentHistoryRequest.serialize, - response_deserializer=environment.LookupEnvironmentHistoryResponse.deserialize, - ) - return self._stubs['lookup_environment_history'] - - -__all__ = ( - 'EnvironmentsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py deleted file mode 100644 index 347981c5..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py +++ /dev/null @@ -1,411 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import environment -from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .grpc import EnvironmentsGrpcTransport - - -class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): - """gRPC AsyncIO backend transport for Environments. - - Service for managing - [Environments][google.cloud.dialogflow.cx.v3.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] = {} - 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_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - Awaitable[environment.ListEnvironmentsResponse]]: - r"""Return a callable for the list environments method over gRPC. - - Returns the list of all environments in the specified - [Agent][google.cloud.dialogflow.cx.v3.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.cx.v3.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 - [Environment][google.cloud.dialogflow.cx.v3.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.cx.v3.Environments/GetEnvironment', - request_serializer=environment.GetEnvironmentRequest.serialize, - response_deserializer=environment.Environment.deserialize, - ) - return self._stubs['get_environment'] - - @property - def create_environment(self) -> Callable[ - [gcdc_environment.CreateEnvironmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create environment method over gRPC. - - Creates an - [Environment][google.cloud.dialogflow.cx.v3.Environment] in the - specified [Agent][google.cloud.dialogflow.cx.v3.Agent]. - - Returns: - Callable[[~.CreateEnvironmentRequest], - 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_environment' not in self._stubs: - self._stubs['create_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Environments/CreateEnvironment', - request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_environment'] - - @property - def update_environment(self) -> Callable[ - [gcdc_environment.UpdateEnvironmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update environment method over gRPC. - - Updates the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Returns: - Callable[[~.UpdateEnvironmentRequest], - 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_environment' not in self._stubs: - self._stubs['update_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Environments/UpdateEnvironment', - request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - 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 - [Environment][google.cloud.dialogflow.cx.v3.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.cx.v3.Environments/DeleteEnvironment', - request_serializer=environment.DeleteEnvironmentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_environment'] - - @property - def lookup_environment_history(self) -> Callable[ - [environment.LookupEnvironmentHistoryRequest], - Awaitable[environment.LookupEnvironmentHistoryResponse]]: - r"""Return a callable for the lookup environment history method over gRPC. - - Looks up the history of the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Returns: - Callable[[~.LookupEnvironmentHistoryRequest], - Awaitable[~.LookupEnvironmentHistoryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'lookup_environment_history' not in self._stubs: - self._stubs['lookup_environment_history'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Environments/LookupEnvironmentHistory', - request_serializer=environment.LookupEnvironmentHistoryRequest.serialize, - response_deserializer=environment.LookupEnvironmentHistoryResponse.deserialize, - ) - return self._stubs['lookup_environment_history'] - - -__all__ = ( - 'EnvironmentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__init__.py deleted file mode 100644 index 6d4dd817..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/__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 ExperimentsClient -from .async_client import ExperimentsAsyncClient - -__all__ = ( - 'ExperimentsClient', - 'ExperimentsAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py deleted file mode 100644 index 03150133..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/async_client.py +++ /dev/null @@ -1,738 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.experiments import pagers -from google.cloud.dialogflowcx_v3.types import experiment -from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport -from .client import ExperimentsClient - - -class ExperimentsAsyncClient: - """Service for managing - [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. - """ - - _client: ExperimentsClient - - DEFAULT_ENDPOINT = ExperimentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ExperimentsClient.DEFAULT_MTLS_ENDPOINT - - experiment_path = staticmethod(ExperimentsClient.experiment_path) - parse_experiment_path = staticmethod(ExperimentsClient.parse_experiment_path) - version_path = staticmethod(ExperimentsClient.version_path) - parse_version_path = staticmethod(ExperimentsClient.parse_version_path) - common_billing_account_path = staticmethod(ExperimentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ExperimentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ExperimentsClient.common_folder_path) - parse_common_folder_path = staticmethod(ExperimentsClient.parse_common_folder_path) - common_organization_path = staticmethod(ExperimentsClient.common_organization_path) - parse_common_organization_path = staticmethod(ExperimentsClient.parse_common_organization_path) - common_project_path = staticmethod(ExperimentsClient.common_project_path) - parse_common_project_path = staticmethod(ExperimentsClient.parse_common_project_path) - common_location_path = staticmethod(ExperimentsClient.common_location_path) - parse_common_location_path = staticmethod(ExperimentsClient.parse_common_location_path) - - @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: - ExperimentsAsyncClient: The constructed client. - """ - return ExperimentsClient.from_service_account_info.__func__(ExperimentsAsyncClient, 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: - ExperimentsAsyncClient: The constructed client. - """ - return ExperimentsClient.from_service_account_file.__func__(ExperimentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> ExperimentsTransport: - """Returns the transport used by the client instance. - - Returns: - ExperimentsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ExperimentsClient).get_transport_class, type(ExperimentsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ExperimentsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the experiments 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, ~.ExperimentsTransport]): 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 = ExperimentsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_experiments(self, - request: experiment.ListExperimentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExperimentsAsyncPager: - r"""Returns the list of all experiments in the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListExperimentsRequest`): - The request object. The request message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. - parent (:class:`str`): - Required. The - [Environment][google.cloud.dialogflow.cx.v3.Environment] - to list all environments for. Format: - ``projects//locations//agents//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.experiments.pagers.ListExperimentsAsyncPager: - The response message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. - - 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 = experiment.ListExperimentsRequest(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_experiments, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListExperimentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_experiment(self, - request: experiment.GetExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Retrieves the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetExperimentRequest`): - The request object. The request message for - [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. - name (:class:`str`): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = experiment.GetExperimentRequest(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_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_experiment(self, - request: gcdc_experiment.CreateExperimentRequest = None, - *, - parent: str = None, - experiment: gcdc_experiment.Experiment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_experiment.Experiment: - r"""Creates an - [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the - specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateExperimentRequest`): - The request object. The request message for - [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. - parent (:class:`str`): - Required. The - [Agent][google.cloud.dialogflow.cx.v3.Agent] to create - an - [Environment][google.cloud.dialogflow.cx.v3.Environment] - for. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - experiment (:class:`google.cloud.dialogflowcx_v3.types.Experiment`): - Required. The experiment to create. - This corresponds to the ``experiment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, experiment]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_experiment.CreateExperimentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if experiment is not None: - request.experiment = experiment - - # 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_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_experiment(self, - request: gcdc_experiment.UpdateExperimentRequest = None, - *, - experiment: gcdc_experiment.Experiment = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_experiment.Experiment: - r"""Updates the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest`): - The request object. The request message for - [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. - experiment (:class:`google.cloud.dialogflowcx_v3.types.Experiment`): - Required. The experiment to update. - This corresponds to the ``experiment`` 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.dialogflowcx_v3.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([experiment, 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 = gcdc_experiment.UpdateExperimentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if experiment is not None: - request.experiment = experiment - if update_mask is not None: - 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_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("experiment.name", request.experiment.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_experiment(self, - request: experiment.DeleteExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest`): - The request object. The request message for - [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. - name (:class:`str`): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment] - to delete. Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = experiment.DeleteExperimentRequest(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_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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 start_experiment(self, - request: experiment.StartExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Starts the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc - only changes the state of experiment from PENDING to RUNNING. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.StartExperimentRequest`): - The request object. The request message for - [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. - name (:class:`str`): - Required. Resource name of the experiment to start. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = experiment.StartExperimentRequest(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.start_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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 stop_experiment(self, - request: experiment.StopExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Stops the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc - only changes the state of experiment from RUNNING to DONE. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.StopExperimentRequest`): - The request object. The request message for - [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. - name (:class:`str`): - Required. Resource name of the experiment to stop. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = experiment.StopExperimentRequest(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.stop_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ExperimentsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py deleted file mode 100644 index f962e435..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/client.py +++ /dev/null @@ -1,934 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.experiments import pagers -from google.cloud.dialogflowcx_v3.types import experiment -from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ExperimentsGrpcTransport -from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport - - -class ExperimentsClientMeta(type): - """Metaclass for the Experiments 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[ExperimentsTransport]] - _transport_registry["grpc"] = ExperimentsGrpcTransport - _transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ExperimentsTransport]: - """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 ExperimentsClient(metaclass=ExperimentsClientMeta): - """Service for managing - [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. - """ - - @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: - ExperimentsClient: 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: - ExperimentsClient: 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) -> ExperimentsTransport: - """Returns the transport used by the client instance. - - Returns: - ExperimentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def experiment_path(project: str,location: str,agent: str,environment: str,experiment: str,) -> str: - """Returns a fully-qualified experiment string.""" - return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format(project=project, location=location, agent=agent, environment=environment, experiment=experiment, ) - - @staticmethod - def parse_experiment_path(path: str) -> Dict[str,str]: - """Parses a experiment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/experiments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: - """Returns a fully-qualified version string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - - @staticmethod - def parse_version_path(path: str) -> Dict[str,str]: - """Parses a version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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, ExperimentsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the experiments 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, ExperimentsTransport]): 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, ExperimentsTransport): - # transport is a ExperimentsTransport 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_experiments(self, - request: experiment.ListExperimentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExperimentsPager: - r"""Returns the list of all experiments in the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListExperimentsRequest): - The request object. The request message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. - parent (str): - Required. The - [Environment][google.cloud.dialogflow.cx.v3.Environment] - to list all environments for. Format: - ``projects//locations//agents//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.experiments.pagers.ListExperimentsPager: - The response message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. - - 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 experiment.ListExperimentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, experiment.ListExperimentsRequest): - request = experiment.ListExperimentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_experiments] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListExperimentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_experiment(self, - request: experiment.GetExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Retrieves the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetExperimentRequest): - The request object. The request message for - [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a experiment.GetExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, experiment.GetExperimentRequest): - request = experiment.GetExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_experiment] - - # Certain fields should be provided 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_experiment(self, - request: gcdc_experiment.CreateExperimentRequest = None, - *, - parent: str = None, - experiment: gcdc_experiment.Experiment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_experiment.Experiment: - r"""Creates an - [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the - specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateExperimentRequest): - The request object. The request message for - [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. - parent (str): - Required. The - [Agent][google.cloud.dialogflow.cx.v3.Agent] to create - an - [Environment][google.cloud.dialogflow.cx.v3.Environment] - for. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - experiment (google.cloud.dialogflowcx_v3.types.Experiment): - Required. The experiment to create. - This corresponds to the ``experiment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, experiment]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_experiment.CreateExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_experiment.CreateExperimentRequest): - request = gcdc_experiment.CreateExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if experiment is not None: - request.experiment = experiment - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_experiment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_experiment(self, - request: gcdc_experiment.UpdateExperimentRequest = None, - *, - experiment: gcdc_experiment.Experiment = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_experiment.Experiment: - r"""Updates the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateExperimentRequest): - The request object. The request message for - [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. - experiment (google.cloud.dialogflowcx_v3.types.Experiment): - Required. The experiment to update. - This corresponds to the ``experiment`` 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.dialogflowcx_v3.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([experiment, 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 gcdc_experiment.UpdateExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_experiment.UpdateExperimentRequest): - request = gcdc_experiment.UpdateExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if experiment is not None: - request.experiment = experiment - if update_mask is not None: - 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_experiment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("experiment.name", request.experiment.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_experiment(self, - request: experiment.DeleteExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Args: - request (google.cloud.dialogflowcx_v3.types.DeleteExperimentRequest): - The request object. The request message for - [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment] - to delete. Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 experiment.DeleteExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, experiment.DeleteExperimentRequest): - request = experiment.DeleteExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_experiment] - - # Certain fields should be 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 start_experiment(self, - request: experiment.StartExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Starts the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc - only changes the state of experiment from PENDING to RUNNING. - - Args: - request (google.cloud.dialogflowcx_v3.types.StartExperimentRequest): - The request object. The request message for - [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. - name (str): - Required. Resource name of the experiment to start. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a experiment.StartExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, experiment.StartExperimentRequest): - request = experiment.StartExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.start_experiment] - - # Certain fields should be provided 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 stop_experiment(self, - request: experiment.StopExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Stops the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc - only changes the state of experiment from RUNNING to DONE. - - Args: - request (google.cloud.dialogflowcx_v3.types.StopExperimentRequest): - The request object. The request message for - [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. - name (str): - Required. Resource name of the experiment to stop. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a experiment.StopExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, experiment.StopExperimentRequest): - request = experiment.StopExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.stop_experiment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ExperimentsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/pagers.py deleted file mode 100644 index 045ae8fb..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/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.dialogflowcx_v3.types import experiment - - -class ListExperimentsPager: - """A pager for iterating through ``list_experiments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``experiments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListExperiments`` requests and continue to iterate - through the ``experiments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` - 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[..., experiment.ListExperimentsResponse], - request: experiment.ListExperimentsRequest, - response: experiment.ListExperimentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListExperimentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListExperimentsResponse): - 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 = experiment.ListExperimentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[experiment.ListExperimentsResponse]: - 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[experiment.Experiment]: - for page in self.pages: - yield from page.experiments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListExperimentsAsyncPager: - """A pager for iterating through ``list_experiments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``experiments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListExperiments`` requests and continue to iterate - through the ``experiments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListExperimentsResponse` - 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[experiment.ListExperimentsResponse]], - request: experiment.ListExperimentsRequest, - response: experiment.ListExperimentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListExperimentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListExperimentsResponse): - 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 = experiment.ListExperimentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[experiment.ListExperimentsResponse]: - 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[experiment.Experiment]: - async def async_generator(): - async for page in self.pages: - for response in page.experiments: - 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/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py deleted file mode 100644 index 80f4c26e..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/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 ExperimentsTransport -from .grpc import ExperimentsGrpcTransport -from .grpc_asyncio import ExperimentsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ExperimentsTransport]] -_transport_registry['grpc'] = ExperimentsGrpcTransport -_transport_registry['grpc_asyncio'] = ExperimentsGrpcAsyncIOTransport - -__all__ = ( - 'ExperimentsTransport', - 'ExperimentsGrpcTransport', - 'ExperimentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py deleted file mode 100644 index 82dd4069..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import experiment -from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -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-dialogflowcx', - ).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 ExperimentsTransport(abc.ABC): - """Abstract transport class for Experiments.""" - - 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_experiments: gapic_v1.method.wrap_method( - self.list_experiments, - default_timeout=None, - client_info=client_info, - ), - self.get_experiment: gapic_v1.method.wrap_method( - self.get_experiment, - default_timeout=None, - client_info=client_info, - ), - self.create_experiment: gapic_v1.method.wrap_method( - self.create_experiment, - default_timeout=None, - client_info=client_info, - ), - self.update_experiment: gapic_v1.method.wrap_method( - self.update_experiment, - default_timeout=None, - client_info=client_info, - ), - self.delete_experiment: gapic_v1.method.wrap_method( - self.delete_experiment, - default_timeout=None, - client_info=client_info, - ), - self.start_experiment: gapic_v1.method.wrap_method( - self.start_experiment, - default_timeout=None, - client_info=client_info, - ), - self.stop_experiment: gapic_v1.method.wrap_method( - self.stop_experiment, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_experiments(self) -> Callable[ - [experiment.ListExperimentsRequest], - Union[ - experiment.ListExperimentsResponse, - Awaitable[experiment.ListExperimentsResponse] - ]]: - raise NotImplementedError() - - @property - def get_experiment(self) -> Callable[ - [experiment.GetExperimentRequest], - Union[ - experiment.Experiment, - Awaitable[experiment.Experiment] - ]]: - raise NotImplementedError() - - @property - def create_experiment(self) -> Callable[ - [gcdc_experiment.CreateExperimentRequest], - Union[ - gcdc_experiment.Experiment, - Awaitable[gcdc_experiment.Experiment] - ]]: - raise NotImplementedError() - - @property - def update_experiment(self) -> Callable[ - [gcdc_experiment.UpdateExperimentRequest], - Union[ - gcdc_experiment.Experiment, - Awaitable[gcdc_experiment.Experiment] - ]]: - raise NotImplementedError() - - @property - def delete_experiment(self) -> Callable[ - [experiment.DeleteExperimentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def start_experiment(self) -> Callable[ - [experiment.StartExperimentRequest], - Union[ - experiment.Experiment, - Awaitable[experiment.Experiment] - ]]: - raise NotImplementedError() - - @property - def stop_experiment(self) -> Callable[ - [experiment.StopExperimentRequest], - Union[ - experiment.Experiment, - Awaitable[experiment.Experiment] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'ExperimentsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py deleted file mode 100644 index 3e5a9901..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.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 Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflowcx_v3.types import experiment -from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -from google.protobuf import empty_pb2 # type: ignore -from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO - - -class ExperimentsGrpcTransport(ExperimentsTransport): - """gRPC backend transport for Experiments. - - Service for managing - [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. - - 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_experiments(self) -> Callable[ - [experiment.ListExperimentsRequest], - experiment.ListExperimentsResponse]: - r"""Return a callable for the list experiments method over gRPC. - - Returns the list of all experiments in the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Returns: - Callable[[~.ListExperimentsRequest], - ~.ListExperimentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_experiments' not in self._stubs: - self._stubs['list_experiments'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/ListExperiments', - request_serializer=experiment.ListExperimentsRequest.serialize, - response_deserializer=experiment.ListExperimentsResponse.deserialize, - ) - return self._stubs['list_experiments'] - - @property - def get_experiment(self) -> Callable[ - [experiment.GetExperimentRequest], - experiment.Experiment]: - r"""Return a callable for the get experiment method over gRPC. - - Retrieves the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Returns: - Callable[[~.GetExperimentRequest], - ~.Experiment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_experiment' not in self._stubs: - self._stubs['get_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/GetExperiment', - request_serializer=experiment.GetExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['get_experiment'] - - @property - def create_experiment(self) -> Callable[ - [gcdc_experiment.CreateExperimentRequest], - gcdc_experiment.Experiment]: - r"""Return a callable for the create experiment method over gRPC. - - Creates an - [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the - specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Returns: - Callable[[~.CreateExperimentRequest], - ~.Experiment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_experiment' not in self._stubs: - self._stubs['create_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/CreateExperiment', - request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, - response_deserializer=gcdc_experiment.Experiment.deserialize, - ) - return self._stubs['create_experiment'] - - @property - def update_experiment(self) -> Callable[ - [gcdc_experiment.UpdateExperimentRequest], - gcdc_experiment.Experiment]: - r"""Return a callable for the update experiment method over gRPC. - - Updates the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Returns: - Callable[[~.UpdateExperimentRequest], - ~.Experiment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_experiment' not in self._stubs: - self._stubs['update_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/UpdateExperiment', - request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, - response_deserializer=gcdc_experiment.Experiment.deserialize, - ) - return self._stubs['update_experiment'] - - @property - def delete_experiment(self) -> Callable[ - [experiment.DeleteExperimentRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete experiment method over gRPC. - - Deletes the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Returns: - Callable[[~.DeleteExperimentRequest], - ~.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_experiment' not in self._stubs: - self._stubs['delete_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/DeleteExperiment', - request_serializer=experiment.DeleteExperimentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_experiment'] - - @property - def start_experiment(self) -> Callable[ - [experiment.StartExperimentRequest], - experiment.Experiment]: - r"""Return a callable for the start experiment method over gRPC. - - Starts the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc - only changes the state of experiment from PENDING to RUNNING. - - Returns: - Callable[[~.StartExperimentRequest], - ~.Experiment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_experiment' not in self._stubs: - self._stubs['start_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/StartExperiment', - request_serializer=experiment.StartExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['start_experiment'] - - @property - def stop_experiment(self) -> Callable[ - [experiment.StopExperimentRequest], - experiment.Experiment]: - r"""Return a callable for the stop experiment method over gRPC. - - Stops the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc - only changes the state of experiment from RUNNING to DONE. - - Returns: - Callable[[~.StopExperimentRequest], - ~.Experiment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_experiment' not in self._stubs: - self._stubs['stop_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/StopExperiment', - request_serializer=experiment.StopExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['stop_experiment'] - - -__all__ = ( - 'ExperimentsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py deleted file mode 100644 index f02dfdbf..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py +++ /dev/null @@ -1,422 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import experiment -from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -from google.protobuf import empty_pb2 # type: ignore -from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO -from .grpc import ExperimentsGrpcTransport - - -class ExperimentsGrpcAsyncIOTransport(ExperimentsTransport): - """gRPC AsyncIO backend transport for Experiments. - - Service for managing - [Experiments][google.cloud.dialogflow.cx.v3.Experiment]. - - 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_experiments(self) -> Callable[ - [experiment.ListExperimentsRequest], - Awaitable[experiment.ListExperimentsResponse]]: - r"""Return a callable for the list experiments method over gRPC. - - Returns the list of all experiments in the specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Returns: - Callable[[~.ListExperimentsRequest], - Awaitable[~.ListExperimentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_experiments' not in self._stubs: - self._stubs['list_experiments'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/ListExperiments', - request_serializer=experiment.ListExperimentsRequest.serialize, - response_deserializer=experiment.ListExperimentsResponse.deserialize, - ) - return self._stubs['list_experiments'] - - @property - def get_experiment(self) -> Callable[ - [experiment.GetExperimentRequest], - Awaitable[experiment.Experiment]]: - r"""Return a callable for the get experiment method over gRPC. - - Retrieves the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Returns: - Callable[[~.GetExperimentRequest], - Awaitable[~.Experiment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_experiment' not in self._stubs: - self._stubs['get_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/GetExperiment', - request_serializer=experiment.GetExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['get_experiment'] - - @property - def create_experiment(self) -> Callable[ - [gcdc_experiment.CreateExperimentRequest], - Awaitable[gcdc_experiment.Experiment]]: - r"""Return a callable for the create experiment method over gRPC. - - Creates an - [Experiment][google.cloud.dialogflow.cx.v3.Experiment] in the - specified - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - - Returns: - Callable[[~.CreateExperimentRequest], - Awaitable[~.Experiment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_experiment' not in self._stubs: - self._stubs['create_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/CreateExperiment', - request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, - response_deserializer=gcdc_experiment.Experiment.deserialize, - ) - return self._stubs['create_experiment'] - - @property - def update_experiment(self) -> Callable[ - [gcdc_experiment.UpdateExperimentRequest], - Awaitable[gcdc_experiment.Experiment]]: - r"""Return a callable for the update experiment method over gRPC. - - Updates the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Returns: - Callable[[~.UpdateExperimentRequest], - Awaitable[~.Experiment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_experiment' not in self._stubs: - self._stubs['update_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/UpdateExperiment', - request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, - response_deserializer=gcdc_experiment.Experiment.deserialize, - ) - return self._stubs['update_experiment'] - - @property - def delete_experiment(self) -> Callable[ - [experiment.DeleteExperimentRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete experiment method over gRPC. - - Deletes the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. - - Returns: - Callable[[~.DeleteExperimentRequest], - 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_experiment' not in self._stubs: - self._stubs['delete_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/DeleteExperiment', - request_serializer=experiment.DeleteExperimentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_experiment'] - - @property - def start_experiment(self) -> Callable[ - [experiment.StartExperimentRequest], - Awaitable[experiment.Experiment]]: - r"""Return a callable for the start experiment method over gRPC. - - Starts the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc - only changes the state of experiment from PENDING to RUNNING. - - Returns: - Callable[[~.StartExperimentRequest], - Awaitable[~.Experiment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_experiment' not in self._stubs: - self._stubs['start_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/StartExperiment', - request_serializer=experiment.StartExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['start_experiment'] - - @property - def stop_experiment(self) -> Callable[ - [experiment.StopExperimentRequest], - Awaitable[experiment.Experiment]]: - r"""Return a callable for the stop experiment method over gRPC. - - Stops the specified - [Experiment][google.cloud.dialogflow.cx.v3.Experiment]. This rpc - only changes the state of experiment from RUNNING to DONE. - - Returns: - Callable[[~.StopExperimentRequest], - Awaitable[~.Experiment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_experiment' not in self._stubs: - self._stubs['stop_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Experiments/StopExperiment', - request_serializer=experiment.StopExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['stop_experiment'] - - -__all__ = ( - 'ExperimentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__init__.py deleted file mode 100644 index 42e3f705..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/__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 FlowsClient -from .async_client import FlowsAsyncClient - -__all__ = ( - 'FlowsClient', - 'FlowsAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py deleted file mode 100644 index 8dcb471b..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/async_client.py +++ /dev/null @@ -1,1008 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.flows import pagers -from google.cloud.dialogflowcx_v3.types import flow -from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import validation_message -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport -from .client import FlowsClient - - -class FlowsAsyncClient: - """Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow].""" - - _client: FlowsClient - - DEFAULT_ENDPOINT = FlowsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = FlowsClient.DEFAULT_MTLS_ENDPOINT - - flow_path = staticmethod(FlowsClient.flow_path) - parse_flow_path = staticmethod(FlowsClient.parse_flow_path) - flow_validation_result_path = staticmethod(FlowsClient.flow_validation_result_path) - parse_flow_validation_result_path = staticmethod(FlowsClient.parse_flow_validation_result_path) - intent_path = staticmethod(FlowsClient.intent_path) - parse_intent_path = staticmethod(FlowsClient.parse_intent_path) - page_path = staticmethod(FlowsClient.page_path) - parse_page_path = staticmethod(FlowsClient.parse_page_path) - transition_route_group_path = staticmethod(FlowsClient.transition_route_group_path) - parse_transition_route_group_path = staticmethod(FlowsClient.parse_transition_route_group_path) - webhook_path = staticmethod(FlowsClient.webhook_path) - parse_webhook_path = staticmethod(FlowsClient.parse_webhook_path) - common_billing_account_path = staticmethod(FlowsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(FlowsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(FlowsClient.common_folder_path) - parse_common_folder_path = staticmethod(FlowsClient.parse_common_folder_path) - common_organization_path = staticmethod(FlowsClient.common_organization_path) - parse_common_organization_path = staticmethod(FlowsClient.parse_common_organization_path) - common_project_path = staticmethod(FlowsClient.common_project_path) - parse_common_project_path = staticmethod(FlowsClient.parse_common_project_path) - common_location_path = staticmethod(FlowsClient.common_location_path) - parse_common_location_path = staticmethod(FlowsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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: - FlowsAsyncClient: The constructed client. - """ - return FlowsClient.from_service_account_info.__func__(FlowsAsyncClient, 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: - FlowsAsyncClient: The constructed client. - """ - return FlowsClient.from_service_account_file.__func__(FlowsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> FlowsTransport: - """Returns the transport used by the client instance. - - Returns: - FlowsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(FlowsClient).get_transport_class, type(FlowsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, FlowsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the flows 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, ~.FlowsTransport]): 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 = FlowsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_flow(self, - request: gcdc_flow.CreateFlowRequest = None, - *, - parent: str = None, - flow: gcdc_flow.Flow = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_flow.Flow: - r"""Creates a flow in the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateFlowRequest`): - The request object. The request message for - [Flows.CreateFlow][google.cloud.dialogflow.cx.v3.Flows.CreateFlow]. - parent (:class:`str`): - Required. The agent to create a flow for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - flow (:class:`google.cloud.dialogflowcx_v3.types.Flow`): - Required. The flow to create. - This corresponds to the ``flow`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, flow]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_flow.CreateFlowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if flow is not None: - request.flow = flow - - # 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_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_flow(self, - request: flow.DeleteFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteFlowRequest`): - The request object. The request message for - [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3.Flows.DeleteFlow]. - name (:class:`str`): - Required. The name of the flow to delete. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = flow.DeleteFlowRequest(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_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_flows(self, - request: flow.ListFlowsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFlowsAsyncPager: - r"""Returns the list of all flows in the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListFlowsRequest`): - The request object. The request message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. - parent (:class:`str`): - Required. The agent containing the flows. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.flows.pagers.ListFlowsAsyncPager: - The response message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. - - 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 = flow.ListFlowsRequest(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_flows, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListFlowsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_flow(self, - request: flow.GetFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.Flow: - r"""Retrieves the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetFlowRequest`): - The request object. The response message for - [Flows.GetFlow][google.cloud.dialogflow.cx.v3.Flows.GetFlow]. - name (:class:`str`): - Required. The name of the flow to get. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = flow.GetFlowRequest(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_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_flow(self, - request: gcdc_flow.UpdateFlowRequest = None, - *, - flow: gcdc_flow.Flow = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_flow.Flow: - r"""Updates the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateFlowRequest`): - The request object. The request message for - [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3.Flows.UpdateFlow]. - flow (:class:`google.cloud.dialogflowcx_v3.types.Flow`): - Required. The flow to update. - This corresponds to the ``flow`` 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 ``update_mask`` is not specified, an error will be - returned. - - 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.dialogflowcx_v3.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([flow, 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 = gcdc_flow.UpdateFlowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if flow is not None: - request.flow = flow - if update_mask is not None: - 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_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("flow.name", request.flow.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def train_flow(self, - request: flow.TrainFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Trains the specified flow. Note that only the flow in - 'draft' environment is trained. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.TrainFlowRequest`): - The request object. The request message for - [Flows.TrainFlow][google.cloud.dialogflow.cx.v3.Flows.TrainFlow]. - name (:class:`str`): - Required. The flow to train. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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 = flow.TrainFlowRequest(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.train_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def validate_flow(self, - request: flow.ValidateFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.FlowValidationResult: - r"""Validates the specified flow and creates or updates - validation results. Please call this API after the - training is completed to get the complete validation - results. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ValidateFlowRequest`): - The request object. The request message for - [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3.Flows.ValidateFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.FlowValidationResult: - The response message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. - - """ - # Create or coerce a protobuf request object. - request = flow.ValidateFlowRequest(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.validate_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_flow_validation_result(self, - request: flow.GetFlowValidationResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.FlowValidationResult: - r"""Gets the latest flow validation result. Flow - validation is performed when ValidateFlow is called. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest`): - The request object. The request message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. - name (:class:`str`): - Required. The flow name. Format: - ``projects//locations//agents//flows//validationResult``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.FlowValidationResult: - The response message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = flow.GetFlowValidationResultRequest(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_flow_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(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_flow(self, - request: flow.ImportFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Imports the specified flow to the specified agent - from a binary file. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ImportFlowRequest`): - The request object. The request message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.ImportFlowResponse` - The response message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. - - """ - # Create or coerce a protobuf request object. - request = flow.ImportFlowRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - flow.ImportFlowResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def export_flow(self, - request: flow.ExportFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ExportFlowRequest`): - The request object. The request message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.ExportFlowResponse` - The response message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. - - """ - # Create or coerce a protobuf request object. - request = flow.ExportFlowRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - flow.ExportFlowResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "FlowsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py deleted file mode 100644 index 9491c46b..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/client.py +++ /dev/null @@ -1,1243 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.flows import pagers -from google.cloud.dialogflowcx_v3.types import flow -from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import validation_message -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import FlowsGrpcTransport -from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport - - -class FlowsClientMeta(type): - """Metaclass for the Flows 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[FlowsTransport]] - _transport_registry["grpc"] = FlowsGrpcTransport - _transport_registry["grpc_asyncio"] = FlowsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[FlowsTransport]: - """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 FlowsClient(metaclass=FlowsClientMeta): - """Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow].""" - - @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: - FlowsClient: 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: - FlowsClient: 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) -> FlowsTransport: - """Returns the transport used by the client instance. - - Returns: - FlowsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_validation_result_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow_validation_result string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_validation_result_path(path: str) -> Dict[str,str]: - """Parses a flow_validation_result path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: - """Returns a fully-qualified page string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - - @staticmethod - def parse_page_path(path: str) -> Dict[str,str]: - """Parses a page path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: - """Returns a fully-qualified transition_route_group string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - - @staticmethod - def parse_transition_route_group_path(path: str) -> Dict[str,str]: - """Parses a transition_route_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, FlowsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the flows 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, FlowsTransport]): 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, FlowsTransport): - # transport is a FlowsTransport 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_flow(self, - request: gcdc_flow.CreateFlowRequest = None, - *, - parent: str = None, - flow: gcdc_flow.Flow = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_flow.Flow: - r"""Creates a flow in the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateFlowRequest): - The request object. The request message for - [Flows.CreateFlow][google.cloud.dialogflow.cx.v3.Flows.CreateFlow]. - parent (str): - Required. The agent to create a flow for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - flow (google.cloud.dialogflowcx_v3.types.Flow): - Required. The flow to create. - This corresponds to the ``flow`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, flow]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_flow.CreateFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_flow.CreateFlowRequest): - request = gcdc_flow.CreateFlowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if flow is not None: - request.flow = flow - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_flow(self, - request: flow.DeleteFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a specified flow. - - Args: - request (google.cloud.dialogflowcx_v3.types.DeleteFlowRequest): - The request object. The request message for - [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3.Flows.DeleteFlow]. - name (str): - Required. The name of the flow to delete. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 flow.DeleteFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.DeleteFlowRequest): - request = flow.DeleteFlowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_flows(self, - request: flow.ListFlowsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFlowsPager: - r"""Returns the list of all flows in the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListFlowsRequest): - The request object. The request message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. - parent (str): - Required. The agent containing the flows. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.flows.pagers.ListFlowsPager: - The response message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. - - 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 flow.ListFlowsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.ListFlowsRequest): - request = flow.ListFlowsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_flows] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListFlowsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_flow(self, - request: flow.GetFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.Flow: - r"""Retrieves the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetFlowRequest): - The request object. The response message for - [Flows.GetFlow][google.cloud.dialogflow.cx.v3.Flows.GetFlow]. - name (str): - Required. The name of the flow to get. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 flow.GetFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.GetFlowRequest): - request = flow.GetFlowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_flow(self, - request: gcdc_flow.UpdateFlowRequest = None, - *, - flow: gcdc_flow.Flow = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_flow.Flow: - r"""Updates the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateFlowRequest): - The request object. The request message for - [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3.Flows.UpdateFlow]. - flow (google.cloud.dialogflowcx_v3.types.Flow): - Required. The flow to update. - This corresponds to the ``flow`` 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 ``update_mask`` is not specified, an error will be - returned. - - 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.dialogflowcx_v3.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([flow, 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 gcdc_flow.UpdateFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_flow.UpdateFlowRequest): - request = gcdc_flow.UpdateFlowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if flow is not None: - request.flow = flow - if update_mask is not None: - 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_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("flow.name", request.flow.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def train_flow(self, - request: flow.TrainFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Trains the specified flow. Note that only the flow in - 'draft' environment is trained. - - Args: - request (google.cloud.dialogflowcx_v3.types.TrainFlowRequest): - The request object. The request message for - [Flows.TrainFlow][google.cloud.dialogflow.cx.v3.Flows.TrainFlow]. - name (str): - Required. The flow to train. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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 flow.TrainFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.TrainFlowRequest): - request = flow.TrainFlowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.train_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def validate_flow(self, - request: flow.ValidateFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.FlowValidationResult: - r"""Validates the specified flow and creates or updates - validation results. Please call this API after the - training is completed to get the complete validation - results. - - Args: - request (google.cloud.dialogflowcx_v3.types.ValidateFlowRequest): - The request object. The request message for - [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3.Flows.ValidateFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.FlowValidationResult: - The response message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a flow.ValidateFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.ValidateFlowRequest): - request = flow.ValidateFlowRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_flow_validation_result(self, - request: flow.GetFlowValidationResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.FlowValidationResult: - r"""Gets the latest flow validation result. Flow - validation is performed when ValidateFlow is called. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetFlowValidationResultRequest): - The request object. The request message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. - name (str): - Required. The flow name. Format: - ``projects//locations//agents//flows//validationResult``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.FlowValidationResult: - The response message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 flow.GetFlowValidationResultRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.GetFlowValidationResultRequest): - request = flow.GetFlowValidationResultRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_flow_validation_result] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_flow(self, - request: flow.ImportFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Imports the specified flow to the specified agent - from a binary file. - - Args: - request (google.cloud.dialogflowcx_v3.types.ImportFlowRequest): - The request object. The request message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.ImportFlowResponse` - The response message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a flow.ImportFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.ImportFlowRequest): - request = flow.ImportFlowRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - flow.ImportFlowResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def export_flow(self, - request: flow.ExportFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. - - Args: - request (google.cloud.dialogflowcx_v3.types.ExportFlowRequest): - The request object. The request message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.ExportFlowResponse` - The response message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a flow.ExportFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.ExportFlowRequest): - request = flow.ExportFlowRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - flow.ExportFlowResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "FlowsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/pagers.py deleted file mode 100644 index a9fc8238..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/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.dialogflowcx_v3.types import flow - - -class ListFlowsPager: - """A pager for iterating through ``list_flows`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``flows`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFlows`` requests and continue to iterate - through the ``flows`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` - 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[..., flow.ListFlowsResponse], - request: flow.ListFlowsRequest, - response: flow.ListFlowsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListFlowsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListFlowsResponse): - 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 = flow.ListFlowsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[flow.ListFlowsResponse]: - 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[flow.Flow]: - for page in self.pages: - yield from page.flows - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFlowsAsyncPager: - """A pager for iterating through ``list_flows`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``flows`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFlows`` requests and continue to iterate - through the ``flows`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListFlowsResponse` - 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[flow.ListFlowsResponse]], - request: flow.ListFlowsRequest, - response: flow.ListFlowsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListFlowsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListFlowsResponse): - 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 = flow.ListFlowsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[flow.ListFlowsResponse]: - 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[flow.Flow]: - async def async_generator(): - async for page in self.pages: - for response in page.flows: - 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/v3/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py deleted file mode 100644 index 4ba28aff..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/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 FlowsTransport -from .grpc import FlowsGrpcTransport -from .grpc_asyncio import FlowsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[FlowsTransport]] -_transport_registry['grpc'] = FlowsGrpcTransport -_transport_registry['grpc_asyncio'] = FlowsGrpcAsyncIOTransport - -__all__ = ( - 'FlowsTransport', - 'FlowsGrpcTransport', - 'FlowsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/base.py deleted file mode 100644 index c7ac3fb3..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/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.dialogflowcx_v3.types import flow -from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow -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-dialogflowcx', - ).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 FlowsTransport(abc.ABC): - """Abstract transport class for Flows.""" - - 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_flow: gapic_v1.method.wrap_method( - self.create_flow, - default_timeout=None, - client_info=client_info, - ), - self.delete_flow: gapic_v1.method.wrap_method( - self.delete_flow, - default_timeout=None, - client_info=client_info, - ), - self.list_flows: gapic_v1.method.wrap_method( - self.list_flows, - default_timeout=None, - client_info=client_info, - ), - self.get_flow: gapic_v1.method.wrap_method( - self.get_flow, - default_timeout=None, - client_info=client_info, - ), - self.update_flow: gapic_v1.method.wrap_method( - self.update_flow, - default_timeout=None, - client_info=client_info, - ), - self.train_flow: gapic_v1.method.wrap_method( - self.train_flow, - default_timeout=None, - client_info=client_info, - ), - self.validate_flow: gapic_v1.method.wrap_method( - self.validate_flow, - default_timeout=None, - client_info=client_info, - ), - self.get_flow_validation_result: gapic_v1.method.wrap_method( - self.get_flow_validation_result, - default_timeout=None, - client_info=client_info, - ), - self.import_flow: gapic_v1.method.wrap_method( - self.import_flow, - default_timeout=None, - client_info=client_info, - ), - self.export_flow: gapic_v1.method.wrap_method( - self.export_flow, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_flow(self) -> Callable[ - [gcdc_flow.CreateFlowRequest], - Union[ - gcdc_flow.Flow, - Awaitable[gcdc_flow.Flow] - ]]: - raise NotImplementedError() - - @property - def delete_flow(self) -> Callable[ - [flow.DeleteFlowRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_flows(self) -> Callable[ - [flow.ListFlowsRequest], - Union[ - flow.ListFlowsResponse, - Awaitable[flow.ListFlowsResponse] - ]]: - raise NotImplementedError() - - @property - def get_flow(self) -> Callable[ - [flow.GetFlowRequest], - Union[ - flow.Flow, - Awaitable[flow.Flow] - ]]: - raise NotImplementedError() - - @property - def update_flow(self) -> Callable[ - [gcdc_flow.UpdateFlowRequest], - Union[ - gcdc_flow.Flow, - Awaitable[gcdc_flow.Flow] - ]]: - raise NotImplementedError() - - @property - def train_flow(self) -> Callable[ - [flow.TrainFlowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def validate_flow(self) -> Callable[ - [flow.ValidateFlowRequest], - Union[ - flow.FlowValidationResult, - Awaitable[flow.FlowValidationResult] - ]]: - raise NotImplementedError() - - @property - def get_flow_validation_result(self) -> Callable[ - [flow.GetFlowValidationResultRequest], - Union[ - flow.FlowValidationResult, - Awaitable[flow.FlowValidationResult] - ]]: - raise NotImplementedError() - - @property - def import_flow(self) -> Callable[ - [flow.ImportFlowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_flow(self) -> Callable[ - [flow.ExportFlowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'FlowsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py deleted file mode 100644 index 45af79c4..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py +++ /dev/null @@ -1,511 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import flow -from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import FlowsTransport, DEFAULT_CLIENT_INFO - - -class FlowsGrpcTransport(FlowsTransport): - """gRPC backend transport for Flows. - - Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow]. - - 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 create_flow(self) -> Callable[ - [gcdc_flow.CreateFlowRequest], - gcdc_flow.Flow]: - r"""Return a callable for the create flow method over gRPC. - - Creates a flow in the specified agent. - - Returns: - Callable[[~.CreateFlowRequest], - ~.Flow]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_flow' not in self._stubs: - self._stubs['create_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/CreateFlow', - request_serializer=gcdc_flow.CreateFlowRequest.serialize, - response_deserializer=gcdc_flow.Flow.deserialize, - ) - return self._stubs['create_flow'] - - @property - def delete_flow(self) -> Callable[ - [flow.DeleteFlowRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete flow method over gRPC. - - Deletes a specified flow. - - Returns: - Callable[[~.DeleteFlowRequest], - ~.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_flow' not in self._stubs: - self._stubs['delete_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/DeleteFlow', - request_serializer=flow.DeleteFlowRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_flow'] - - @property - def list_flows(self) -> Callable[ - [flow.ListFlowsRequest], - flow.ListFlowsResponse]: - r"""Return a callable for the list flows method over gRPC. - - Returns the list of all flows in the specified agent. - - Returns: - Callable[[~.ListFlowsRequest], - ~.ListFlowsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_flows' not in self._stubs: - self._stubs['list_flows'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/ListFlows', - request_serializer=flow.ListFlowsRequest.serialize, - response_deserializer=flow.ListFlowsResponse.deserialize, - ) - return self._stubs['list_flows'] - - @property - def get_flow(self) -> Callable[ - [flow.GetFlowRequest], - flow.Flow]: - r"""Return a callable for the get flow method over gRPC. - - Retrieves the specified flow. - - Returns: - Callable[[~.GetFlowRequest], - ~.Flow]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_flow' not in self._stubs: - self._stubs['get_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/GetFlow', - request_serializer=flow.GetFlowRequest.serialize, - response_deserializer=flow.Flow.deserialize, - ) - return self._stubs['get_flow'] - - @property - def update_flow(self) -> Callable[ - [gcdc_flow.UpdateFlowRequest], - gcdc_flow.Flow]: - r"""Return a callable for the update flow method over gRPC. - - Updates the specified flow. - - Returns: - Callable[[~.UpdateFlowRequest], - ~.Flow]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_flow' not in self._stubs: - self._stubs['update_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/UpdateFlow', - request_serializer=gcdc_flow.UpdateFlowRequest.serialize, - response_deserializer=gcdc_flow.Flow.deserialize, - ) - return self._stubs['update_flow'] - - @property - def train_flow(self) -> Callable[ - [flow.TrainFlowRequest], - operations_pb2.Operation]: - r"""Return a callable for the train flow method over gRPC. - - Trains the specified flow. Note that only the flow in - 'draft' environment is trained. - - Returns: - Callable[[~.TrainFlowRequest], - ~.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_flow' not in self._stubs: - self._stubs['train_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/TrainFlow', - request_serializer=flow.TrainFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_flow'] - - @property - def validate_flow(self) -> Callable[ - [flow.ValidateFlowRequest], - flow.FlowValidationResult]: - r"""Return a callable for the validate flow method over gRPC. - - Validates the specified flow and creates or updates - validation results. Please call this API after the - training is completed to get the complete validation - results. - - Returns: - Callable[[~.ValidateFlowRequest], - ~.FlowValidationResult]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_flow' not in self._stubs: - self._stubs['validate_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/ValidateFlow', - request_serializer=flow.ValidateFlowRequest.serialize, - response_deserializer=flow.FlowValidationResult.deserialize, - ) - return self._stubs['validate_flow'] - - @property - def get_flow_validation_result(self) -> Callable[ - [flow.GetFlowValidationResultRequest], - flow.FlowValidationResult]: - r"""Return a callable for the get flow validation result method over gRPC. - - Gets the latest flow validation result. Flow - validation is performed when ValidateFlow is called. - - Returns: - Callable[[~.GetFlowValidationResultRequest], - ~.FlowValidationResult]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_flow_validation_result' not in self._stubs: - self._stubs['get_flow_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/GetFlowValidationResult', - request_serializer=flow.GetFlowValidationResultRequest.serialize, - response_deserializer=flow.FlowValidationResult.deserialize, - ) - return self._stubs['get_flow_validation_result'] - - @property - def import_flow(self) -> Callable[ - [flow.ImportFlowRequest], - operations_pb2.Operation]: - r"""Return a callable for the import flow method over gRPC. - - Imports the specified flow to the specified agent - from a binary file. - - Returns: - Callable[[~.ImportFlowRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_flow' not in self._stubs: - self._stubs['import_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/ImportFlow', - request_serializer=flow.ImportFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_flow'] - - @property - def export_flow(self) -> Callable[ - [flow.ExportFlowRequest], - operations_pb2.Operation]: - r"""Return a callable for the export flow method over gRPC. - - Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. - - Returns: - Callable[[~.ExportFlowRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_flow' not in self._stubs: - self._stubs['export_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/ExportFlow', - request_serializer=flow.ExportFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_flow'] - - -__all__ = ( - 'FlowsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py deleted file mode 100644 index 05379556..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py +++ /dev/null @@ -1,515 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import flow -from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import FlowsTransport, DEFAULT_CLIENT_INFO -from .grpc import FlowsGrpcTransport - - -class FlowsGrpcAsyncIOTransport(FlowsTransport): - """gRPC AsyncIO backend transport for Flows. - - Service for managing [Flows][google.cloud.dialogflow.cx.v3.Flow]. - - 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 create_flow(self) -> Callable[ - [gcdc_flow.CreateFlowRequest], - Awaitable[gcdc_flow.Flow]]: - r"""Return a callable for the create flow method over gRPC. - - Creates a flow in the specified agent. - - Returns: - Callable[[~.CreateFlowRequest], - Awaitable[~.Flow]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_flow' not in self._stubs: - self._stubs['create_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/CreateFlow', - request_serializer=gcdc_flow.CreateFlowRequest.serialize, - response_deserializer=gcdc_flow.Flow.deserialize, - ) - return self._stubs['create_flow'] - - @property - def delete_flow(self) -> Callable[ - [flow.DeleteFlowRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete flow method over gRPC. - - Deletes a specified flow. - - Returns: - Callable[[~.DeleteFlowRequest], - 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_flow' not in self._stubs: - self._stubs['delete_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/DeleteFlow', - request_serializer=flow.DeleteFlowRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_flow'] - - @property - def list_flows(self) -> Callable[ - [flow.ListFlowsRequest], - Awaitable[flow.ListFlowsResponse]]: - r"""Return a callable for the list flows method over gRPC. - - Returns the list of all flows in the specified agent. - - Returns: - Callable[[~.ListFlowsRequest], - Awaitable[~.ListFlowsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_flows' not in self._stubs: - self._stubs['list_flows'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/ListFlows', - request_serializer=flow.ListFlowsRequest.serialize, - response_deserializer=flow.ListFlowsResponse.deserialize, - ) - return self._stubs['list_flows'] - - @property - def get_flow(self) -> Callable[ - [flow.GetFlowRequest], - Awaitable[flow.Flow]]: - r"""Return a callable for the get flow method over gRPC. - - Retrieves the specified flow. - - Returns: - Callable[[~.GetFlowRequest], - Awaitable[~.Flow]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_flow' not in self._stubs: - self._stubs['get_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/GetFlow', - request_serializer=flow.GetFlowRequest.serialize, - response_deserializer=flow.Flow.deserialize, - ) - return self._stubs['get_flow'] - - @property - def update_flow(self) -> Callable[ - [gcdc_flow.UpdateFlowRequest], - Awaitable[gcdc_flow.Flow]]: - r"""Return a callable for the update flow method over gRPC. - - Updates the specified flow. - - Returns: - Callable[[~.UpdateFlowRequest], - Awaitable[~.Flow]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_flow' not in self._stubs: - self._stubs['update_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/UpdateFlow', - request_serializer=gcdc_flow.UpdateFlowRequest.serialize, - response_deserializer=gcdc_flow.Flow.deserialize, - ) - return self._stubs['update_flow'] - - @property - def train_flow(self) -> Callable[ - [flow.TrainFlowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the train flow method over gRPC. - - Trains the specified flow. Note that only the flow in - 'draft' environment is trained. - - Returns: - Callable[[~.TrainFlowRequest], - 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_flow' not in self._stubs: - self._stubs['train_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/TrainFlow', - request_serializer=flow.TrainFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_flow'] - - @property - def validate_flow(self) -> Callable[ - [flow.ValidateFlowRequest], - Awaitable[flow.FlowValidationResult]]: - r"""Return a callable for the validate flow method over gRPC. - - Validates the specified flow and creates or updates - validation results. Please call this API after the - training is completed to get the complete validation - results. - - Returns: - Callable[[~.ValidateFlowRequest], - Awaitable[~.FlowValidationResult]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_flow' not in self._stubs: - self._stubs['validate_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/ValidateFlow', - request_serializer=flow.ValidateFlowRequest.serialize, - response_deserializer=flow.FlowValidationResult.deserialize, - ) - return self._stubs['validate_flow'] - - @property - def get_flow_validation_result(self) -> Callable[ - [flow.GetFlowValidationResultRequest], - Awaitable[flow.FlowValidationResult]]: - r"""Return a callable for the get flow validation result method over gRPC. - - Gets the latest flow validation result. Flow - validation is performed when ValidateFlow is called. - - Returns: - Callable[[~.GetFlowValidationResultRequest], - Awaitable[~.FlowValidationResult]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_flow_validation_result' not in self._stubs: - self._stubs['get_flow_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/GetFlowValidationResult', - request_serializer=flow.GetFlowValidationResultRequest.serialize, - response_deserializer=flow.FlowValidationResult.deserialize, - ) - return self._stubs['get_flow_validation_result'] - - @property - def import_flow(self) -> Callable[ - [flow.ImportFlowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import flow method over gRPC. - - Imports the specified flow to the specified agent - from a binary file. - - Returns: - Callable[[~.ImportFlowRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_flow' not in self._stubs: - self._stubs['import_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/ImportFlow', - request_serializer=flow.ImportFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_flow'] - - @property - def export_flow(self) -> Callable[ - [flow.ExportFlowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the export flow method over gRPC. - - Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. - - Returns: - Callable[[~.ExportFlowRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_flow' not in self._stubs: - self._stubs['export_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Flows/ExportFlow', - request_serializer=flow.ExportFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_flow'] - - -__all__ = ( - 'FlowsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/__init__.py deleted file mode 100644 index 8204500f..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py deleted file mode 100644 index 0c7cd7e0..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/async_client.py +++ /dev/null @@ -1,580 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.intents import pagers -from google.cloud.dialogflowcx_v3.types import intent -from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -from google.protobuf import field_mask_pb2 # 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.cx.v3.Intent]. - """ - - _client: IntentsClient - - DEFAULT_ENDPOINT = IntentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = IntentsClient.DEFAULT_MTLS_ENDPOINT - - entity_type_path = staticmethod(IntentsClient.entity_type_path) - parse_entity_type_path = staticmethod(IntentsClient.parse_entity_type_path) - intent_path = staticmethod(IntentsClient.intent_path) - parse_intent_path = staticmethod(IntentsClient.parse_intent_path) - common_billing_account_path = staticmethod(IntentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(IntentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(IntentsClient.common_folder_path) - parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) - common_organization_path = staticmethod(IntentsClient.common_organization_path) - parse_common_organization_path = staticmethod(IntentsClient.parse_common_organization_path) - common_project_path = staticmethod(IntentsClient.common_project_path) - parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) - common_location_path = staticmethod(IntentsClient.common_location_path) - parse_common_location_path = staticmethod(IntentsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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, - 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.dialogflowcx_v3.types.ListIntentsRequest`): - The request object. The request message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. - parent (:class:`str`): - Required. The agent to list all intents for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.intents.pagers.ListIntentsAsyncPager: - The response message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3.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]) - if request is not 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 - - # 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, - 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.dialogflowcx_v3.types.GetIntentRequest`): - The request object. The request message for - [Intents.GetIntent][google.cloud.dialogflow.cx.v3.Intents.GetIntent]. - name (:class:`str`): - Required. The name of the intent. Format: - ``projects//locations//agents//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. - - Returns: - google.cloud.dialogflowcx_v3.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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.GetIntentRequest(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_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: gcdc_intent.CreateIntentRequest = None, - *, - parent: str = None, - intent: gcdc_intent.Intent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_intent.Intent: - r"""Creates an intent in the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateIntentRequest`): - The request object. The request message for - [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent]. - parent (:class:`str`): - Required. The agent to create an intent for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent (:class:`google.cloud.dialogflowcx_v3.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. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_intent.CreateIntentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if intent is not None: - request.intent = intent - - # 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: gcdc_intent.UpdateIntentRequest = None, - *, - intent: gcdc_intent.Intent = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_intent.Intent: - r"""Updates the specified intent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateIntentRequest`): - The request object. The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent]. - intent (:class:`google.cloud.dialogflowcx_v3.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`): - 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.dialogflowcx_v3.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity 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]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_intent.UpdateIntentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if intent is not None: - request.intent = intent - if update_mask is not None: - 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. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteIntentRequest`): - The request object. The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3.Intents.DeleteIntent]. - name (:class:`str`): - Required. The name of the intent to delete. Format: - ``projects//locations//agents//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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "IntentsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py deleted file mode 100644 index 364a8eae..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/client.py +++ /dev/null @@ -1,776 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.intents import pagers -from google.cloud.dialogflowcx_v3.types import intent -from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -from google.protobuf import field_mask_pb2 # 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.cx.v3.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 entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/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, - 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.dialogflowcx_v3.types.ListIntentsRequest): - The request object. The request message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. - parent (str): - Required. The agent to list all intents for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.intents.pagers.ListIntentsPager: - The response message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3.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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is 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 - - # 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, - 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.dialogflowcx_v3.types.GetIntentRequest): - The request object. The request message for - [Intents.GetIntent][google.cloud.dialogflow.cx.v3.Intents.GetIntent]. - name (str): - Required. The name of the intent. Format: - ``projects//locations//agents//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. - - Returns: - google.cloud.dialogflowcx_v3.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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.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 - - # 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: gcdc_intent.CreateIntentRequest = None, - *, - parent: str = None, - intent: gcdc_intent.Intent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_intent.Intent: - r"""Creates an intent in the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateIntentRequest): - The request object. The request message for - [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent]. - parent (str): - Required. The agent to create an intent for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent (google.cloud.dialogflowcx_v3.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. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_intent.CreateIntentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_intent.CreateIntentRequest): - request = gcdc_intent.CreateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if intent is not None: - request.intent = intent - - # 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: gcdc_intent.UpdateIntentRequest = None, - *, - intent: gcdc_intent.Intent = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_intent.Intent: - r"""Updates the specified intent. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateIntentRequest): - The request object. The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent]. - intent (google.cloud.dialogflowcx_v3.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): - 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.dialogflowcx_v3.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_intent.UpdateIntentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_intent.UpdateIntentRequest): - request = gcdc_intent.UpdateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if intent is not None: - request.intent = intent - if update_mask is not None: - 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. - - Args: - request (google.cloud.dialogflowcx_v3.types.DeleteIntentRequest): - The request object. The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3.Intents.DeleteIntent]. - name (str): - Required. The name of the intent to delete. Format: - ``projects//locations//agents//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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "IntentsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/pagers.py deleted file mode 100644 index 8883d7c0..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import intent - - -class ListIntentsPager: - """A pager for iterating through ``list_intents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListIntentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListIntentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.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/v3/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py deleted file mode 100644 index aa8039bb..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/intents/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/base.py deleted file mode 100644 index 02323468..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/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.dialogflowcx_v3.types import intent -from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -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-dialogflowcx', - ).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, - ), - } - - @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[ - [gcdc_intent.CreateIntentRequest], - Union[ - gcdc_intent.Intent, - Awaitable[gcdc_intent.Intent] - ]]: - raise NotImplementedError() - - @property - def update_intent(self) -> Callable[ - [gcdc_intent.UpdateIntentRequest], - Union[ - gcdc_intent.Intent, - Awaitable[gcdc_intent.Intent] - ]]: - raise NotImplementedError() - - @property - def delete_intent(self) -> Callable[ - [intent.DeleteIntentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'IntentsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py deleted file mode 100644 index 3a2e0b75..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/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.dialogflowcx_v3.types import intent -from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -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.cx.v3.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] = {} - - 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_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.cx.v3.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.cx.v3.Intents/GetIntent', - request_serializer=intent.GetIntentRequest.serialize, - response_deserializer=intent.Intent.deserialize, - ) - return self._stubs['get_intent'] - - @property - def create_intent(self) -> Callable[ - [gcdc_intent.CreateIntentRequest], - gcdc_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.cx.v3.Intents/CreateIntent', - request_serializer=gcdc_intent.CreateIntentRequest.serialize, - response_deserializer=gcdc_intent.Intent.deserialize, - ) - return self._stubs['create_intent'] - - @property - def update_intent(self) -> Callable[ - [gcdc_intent.UpdateIntentRequest], - gcdc_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.cx.v3.Intents/UpdateIntent', - request_serializer=gcdc_intent.UpdateIntentRequest.serialize, - response_deserializer=gcdc_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. - - 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.cx.v3.Intents/DeleteIntent', - request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_intent'] - - -__all__ = ( - 'IntentsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py deleted file mode 100644 index ca672c54..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/intents/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.dialogflowcx_v3.types import intent -from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -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.cx.v3.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] = {} - - 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_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.cx.v3.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.cx.v3.Intents/GetIntent', - request_serializer=intent.GetIntentRequest.serialize, - response_deserializer=intent.Intent.deserialize, - ) - return self._stubs['get_intent'] - - @property - def create_intent(self) -> Callable[ - [gcdc_intent.CreateIntentRequest], - Awaitable[gcdc_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.cx.v3.Intents/CreateIntent', - request_serializer=gcdc_intent.CreateIntentRequest.serialize, - response_deserializer=gcdc_intent.Intent.deserialize, - ) - return self._stubs['create_intent'] - - @property - def update_intent(self) -> Callable[ - [gcdc_intent.UpdateIntentRequest], - Awaitable[gcdc_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.cx.v3.Intents/UpdateIntent', - request_serializer=gcdc_intent.UpdateIntentRequest.serialize, - response_deserializer=gcdc_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. - - 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.cx.v3.Intents/DeleteIntent', - request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_intent'] - - -__all__ = ( - 'IntentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__init__.py deleted file mode 100644 index b8668f72..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/__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 PagesClient -from .async_client import PagesAsyncClient - -__all__ = ( - 'PagesClient', - 'PagesAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py deleted file mode 100644 index e004686a..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/async_client.py +++ /dev/null @@ -1,631 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.pages import pagers -from google.cloud.dialogflowcx_v3.types import fulfillment -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import page as gcdc_page -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport -from .client import PagesClient - - -class PagesAsyncClient: - """Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page].""" - - _client: PagesClient - - DEFAULT_ENDPOINT = PagesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PagesClient.DEFAULT_MTLS_ENDPOINT - - entity_type_path = staticmethod(PagesClient.entity_type_path) - parse_entity_type_path = staticmethod(PagesClient.parse_entity_type_path) - flow_path = staticmethod(PagesClient.flow_path) - parse_flow_path = staticmethod(PagesClient.parse_flow_path) - intent_path = staticmethod(PagesClient.intent_path) - parse_intent_path = staticmethod(PagesClient.parse_intent_path) - page_path = staticmethod(PagesClient.page_path) - parse_page_path = staticmethod(PagesClient.parse_page_path) - transition_route_group_path = staticmethod(PagesClient.transition_route_group_path) - parse_transition_route_group_path = staticmethod(PagesClient.parse_transition_route_group_path) - webhook_path = staticmethod(PagesClient.webhook_path) - parse_webhook_path = staticmethod(PagesClient.parse_webhook_path) - common_billing_account_path = staticmethod(PagesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PagesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PagesClient.common_folder_path) - parse_common_folder_path = staticmethod(PagesClient.parse_common_folder_path) - common_organization_path = staticmethod(PagesClient.common_organization_path) - parse_common_organization_path = staticmethod(PagesClient.parse_common_organization_path) - common_project_path = staticmethod(PagesClient.common_project_path) - parse_common_project_path = staticmethod(PagesClient.parse_common_project_path) - common_location_path = staticmethod(PagesClient.common_location_path) - parse_common_location_path = staticmethod(PagesClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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: - PagesAsyncClient: The constructed client. - """ - return PagesClient.from_service_account_info.__func__(PagesAsyncClient, 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: - PagesAsyncClient: The constructed client. - """ - return PagesClient.from_service_account_file.__func__(PagesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> PagesTransport: - """Returns the transport used by the client instance. - - Returns: - PagesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PagesClient).get_transport_class, type(PagesClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PagesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the pages 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, ~.PagesTransport]): 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 = PagesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_pages(self, - request: page.ListPagesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPagesAsyncPager: - r"""Returns the list of all pages in the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListPagesRequest`): - The request object. The request message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. - parent (:class:`str`): - Required. The flow to list all pages for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.pages.pagers.ListPagesAsyncPager: - The response message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. - - 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 = page.ListPagesRequest(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_pages, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListPagesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_page(self, - request: page.GetPageRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> page.Page: - r"""Retrieves the specified page. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetPageRequest`): - The request object. The request message for - [Pages.GetPage][google.cloud.dialogflow.cx.v3.Pages.GetPage]. - name (:class:`str`): - Required. The name of the page. Format: - ``projects//locations//agents//flows//pages/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = page.GetPageRequest(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_page, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_page(self, - request: gcdc_page.CreatePageRequest = None, - *, - parent: str = None, - page: gcdc_page.Page = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_page.Page: - r"""Creates a page in the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreatePageRequest`): - The request object. The request message for - [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage]. - parent (:class:`str`): - Required. The flow to create a page for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - page (:class:`google.cloud.dialogflowcx_v3.types.Page`): - Required. The page to create. - This corresponds to the ``page`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, page]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_page.CreatePageRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if page is not None: - request.page = page - - # 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_page, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_page(self, - request: gcdc_page.UpdatePageRequest = None, - *, - page: gcdc_page.Page = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_page.Page: - r"""Updates the specified page. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdatePageRequest`): - The request object. The request message for - [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage]. - page (:class:`google.cloud.dialogflowcx_v3.types.Page`): - Required. The page to update. - This corresponds to the ``page`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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.dialogflowcx_v3.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([page, 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 = gcdc_page.UpdatePageRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if page is not None: - request.page = page - if update_mask is not None: - 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_page, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("page.name", request.page.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_page(self, - request: page.DeletePageRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified page. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeletePageRequest`): - The request object. The request message for - [Pages.DeletePage][google.cloud.dialogflow.cx.v3.Pages.DeletePage]. - name (:class:`str`): - Required. The name of the page to delete. Format: - ``projects//locations//agents//Flows//pages/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = page.DeletePageRequest(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_page, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PagesAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py deleted file mode 100644 index 43b5da5c..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/client.py +++ /dev/null @@ -1,863 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.pages import pagers -from google.cloud.dialogflowcx_v3.types import fulfillment -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import page as gcdc_page -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PagesGrpcTransport -from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport - - -class PagesClientMeta(type): - """Metaclass for the Pages 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[PagesTransport]] - _transport_registry["grpc"] = PagesGrpcTransport - _transport_registry["grpc_asyncio"] = PagesGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PagesTransport]: - """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 PagesClient(metaclass=PagesClientMeta): - """Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page].""" - - @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: - PagesClient: 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: - PagesClient: 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) -> PagesTransport: - """Returns the transport used by the client instance. - - Returns: - PagesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: - """Returns a fully-qualified page string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - - @staticmethod - def parse_page_path(path: str) -> Dict[str,str]: - """Parses a page path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: - """Returns a fully-qualified transition_route_group string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - - @staticmethod - def parse_transition_route_group_path(path: str) -> Dict[str,str]: - """Parses a transition_route_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, PagesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the pages 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, PagesTransport]): 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, PagesTransport): - # transport is a PagesTransport 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_pages(self, - request: page.ListPagesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPagesPager: - r"""Returns the list of all pages in the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListPagesRequest): - The request object. The request message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. - parent (str): - Required. The flow to list all pages for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.pages.pagers.ListPagesPager: - The response message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. - - 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 page.ListPagesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, page.ListPagesRequest): - request = page.ListPagesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_pages] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListPagesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_page(self, - request: page.GetPageRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> page.Page: - r"""Retrieves the specified page. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetPageRequest): - The request object. The request message for - [Pages.GetPage][google.cloud.dialogflow.cx.v3.Pages.GetPage]. - name (str): - Required. The name of the page. Format: - ``projects//locations//agents//flows//pages/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 page.GetPageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, page.GetPageRequest): - request = page.GetPageRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_page] - - # Certain fields should be provided 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_page(self, - request: gcdc_page.CreatePageRequest = None, - *, - parent: str = None, - page: gcdc_page.Page = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_page.Page: - r"""Creates a page in the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreatePageRequest): - The request object. The request message for - [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage]. - parent (str): - Required. The flow to create a page for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - page (google.cloud.dialogflowcx_v3.types.Page): - Required. The page to create. - This corresponds to the ``page`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, page]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_page.CreatePageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_page.CreatePageRequest): - request = gcdc_page.CreatePageRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if page is not None: - request.page = page - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_page] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_page(self, - request: gcdc_page.UpdatePageRequest = None, - *, - page: gcdc_page.Page = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_page.Page: - r"""Updates the specified page. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdatePageRequest): - The request object. The request message for - [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage]. - page (google.cloud.dialogflowcx_v3.types.Page): - Required. The page to update. - This corresponds to the ``page`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.dialogflowcx_v3.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([page, 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 gcdc_page.UpdatePageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_page.UpdatePageRequest): - request = gcdc_page.UpdatePageRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if page is not None: - request.page = page - if update_mask is not None: - 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_page] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("page.name", request.page.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_page(self, - request: page.DeletePageRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified page. - - Args: - request (google.cloud.dialogflowcx_v3.types.DeletePageRequest): - The request object. The request message for - [Pages.DeletePage][google.cloud.dialogflow.cx.v3.Pages.DeletePage]. - name (str): - Required. The name of the page to delete. Format: - ``projects//locations//agents//Flows//pages/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 page.DeletePageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, page.DeletePageRequest): - request = page.DeletePageRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_page] - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PagesClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/pagers.py deleted file mode 100644 index fb23ff83..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/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.dialogflowcx_v3.types import page - - -class ListPagesPager: - """A pager for iterating through ``list_pages`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``pages`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPages`` requests and continue to iterate - through the ``pages`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` - 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[..., page.ListPagesResponse], - request: page.ListPagesRequest, - response: page.ListPagesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListPagesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListPagesResponse): - 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 = page.ListPagesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[page.ListPagesResponse]: - 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[page.Page]: - for page in self.pages: - yield from page.pages - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPagesAsyncPager: - """A pager for iterating through ``list_pages`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``pages`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPages`` requests and continue to iterate - through the ``pages`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListPagesResponse` - 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[page.ListPagesResponse]], - request: page.ListPagesRequest, - response: page.ListPagesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListPagesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListPagesResponse): - 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 = page.ListPagesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[page.ListPagesResponse]: - 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[page.Page]: - async def async_generator(): - async for page in self.pages: - for response in page.pages: - 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/v3/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py deleted file mode 100644 index ee74f029..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/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 PagesTransport -from .grpc import PagesGrpcTransport -from .grpc_asyncio import PagesGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PagesTransport]] -_transport_registry['grpc'] = PagesGrpcTransport -_transport_registry['grpc_asyncio'] = PagesGrpcAsyncIOTransport - -__all__ = ( - 'PagesTransport', - 'PagesGrpcTransport', - 'PagesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/base.py deleted file mode 100644 index f141931d..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/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.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import page as gcdc_page -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-dialogflowcx', - ).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 PagesTransport(abc.ABC): - """Abstract transport class for Pages.""" - - 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_pages: gapic_v1.method.wrap_method( - self.list_pages, - default_timeout=None, - client_info=client_info, - ), - self.get_page: gapic_v1.method.wrap_method( - self.get_page, - default_timeout=None, - client_info=client_info, - ), - self.create_page: gapic_v1.method.wrap_method( - self.create_page, - default_timeout=None, - client_info=client_info, - ), - self.update_page: gapic_v1.method.wrap_method( - self.update_page, - default_timeout=None, - client_info=client_info, - ), - self.delete_page: gapic_v1.method.wrap_method( - self.delete_page, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_pages(self) -> Callable[ - [page.ListPagesRequest], - Union[ - page.ListPagesResponse, - Awaitable[page.ListPagesResponse] - ]]: - raise NotImplementedError() - - @property - def get_page(self) -> Callable[ - [page.GetPageRequest], - Union[ - page.Page, - Awaitable[page.Page] - ]]: - raise NotImplementedError() - - @property - def create_page(self) -> Callable[ - [gcdc_page.CreatePageRequest], - Union[ - gcdc_page.Page, - Awaitable[gcdc_page.Page] - ]]: - raise NotImplementedError() - - @property - def update_page(self) -> Callable[ - [gcdc_page.UpdatePageRequest], - Union[ - gcdc_page.Page, - Awaitable[gcdc_page.Page] - ]]: - raise NotImplementedError() - - @property - def delete_page(self) -> Callable[ - [page.DeletePageRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'PagesTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py deleted file mode 100644 index a0448cdd..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py +++ /dev/null @@ -1,354 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import page as gcdc_page -from google.protobuf import empty_pb2 # type: ignore -from .base import PagesTransport, DEFAULT_CLIENT_INFO - - -class PagesGrpcTransport(PagesTransport): - """gRPC backend transport for Pages. - - Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page]. - - 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_pages(self) -> Callable[ - [page.ListPagesRequest], - page.ListPagesResponse]: - r"""Return a callable for the list pages method over gRPC. - - Returns the list of all pages in the specified flow. - - Returns: - Callable[[~.ListPagesRequest], - ~.ListPagesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_pages' not in self._stubs: - self._stubs['list_pages'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Pages/ListPages', - request_serializer=page.ListPagesRequest.serialize, - response_deserializer=page.ListPagesResponse.deserialize, - ) - return self._stubs['list_pages'] - - @property - def get_page(self) -> Callable[ - [page.GetPageRequest], - page.Page]: - r"""Return a callable for the get page method over gRPC. - - Retrieves the specified page. - - Returns: - Callable[[~.GetPageRequest], - ~.Page]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_page' not in self._stubs: - self._stubs['get_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Pages/GetPage', - request_serializer=page.GetPageRequest.serialize, - response_deserializer=page.Page.deserialize, - ) - return self._stubs['get_page'] - - @property - def create_page(self) -> Callable[ - [gcdc_page.CreatePageRequest], - gcdc_page.Page]: - r"""Return a callable for the create page method over gRPC. - - Creates a page in the specified flow. - - Returns: - Callable[[~.CreatePageRequest], - ~.Page]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_page' not in self._stubs: - self._stubs['create_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Pages/CreatePage', - request_serializer=gcdc_page.CreatePageRequest.serialize, - response_deserializer=gcdc_page.Page.deserialize, - ) - return self._stubs['create_page'] - - @property - def update_page(self) -> Callable[ - [gcdc_page.UpdatePageRequest], - gcdc_page.Page]: - r"""Return a callable for the update page method over gRPC. - - Updates the specified page. - - Returns: - Callable[[~.UpdatePageRequest], - ~.Page]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_page' not in self._stubs: - self._stubs['update_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Pages/UpdatePage', - request_serializer=gcdc_page.UpdatePageRequest.serialize, - response_deserializer=gcdc_page.Page.deserialize, - ) - return self._stubs['update_page'] - - @property - def delete_page(self) -> Callable[ - [page.DeletePageRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete page method over gRPC. - - Deletes the specified page. - - Returns: - Callable[[~.DeletePageRequest], - ~.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_page' not in self._stubs: - self._stubs['delete_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Pages/DeletePage', - request_serializer=page.DeletePageRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_page'] - - -__all__ = ( - 'PagesGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py deleted file mode 100644 index 4892a267..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py +++ /dev/null @@ -1,358 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import page as gcdc_page -from google.protobuf import empty_pb2 # type: ignore -from .base import PagesTransport, DEFAULT_CLIENT_INFO -from .grpc import PagesGrpcTransport - - -class PagesGrpcAsyncIOTransport(PagesTransport): - """gRPC AsyncIO backend transport for Pages. - - Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page]. - - 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_pages(self) -> Callable[ - [page.ListPagesRequest], - Awaitable[page.ListPagesResponse]]: - r"""Return a callable for the list pages method over gRPC. - - Returns the list of all pages in the specified flow. - - Returns: - Callable[[~.ListPagesRequest], - Awaitable[~.ListPagesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_pages' not in self._stubs: - self._stubs['list_pages'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Pages/ListPages', - request_serializer=page.ListPagesRequest.serialize, - response_deserializer=page.ListPagesResponse.deserialize, - ) - return self._stubs['list_pages'] - - @property - def get_page(self) -> Callable[ - [page.GetPageRequest], - Awaitable[page.Page]]: - r"""Return a callable for the get page method over gRPC. - - Retrieves the specified page. - - Returns: - Callable[[~.GetPageRequest], - Awaitable[~.Page]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_page' not in self._stubs: - self._stubs['get_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Pages/GetPage', - request_serializer=page.GetPageRequest.serialize, - response_deserializer=page.Page.deserialize, - ) - return self._stubs['get_page'] - - @property - def create_page(self) -> Callable[ - [gcdc_page.CreatePageRequest], - Awaitable[gcdc_page.Page]]: - r"""Return a callable for the create page method over gRPC. - - Creates a page in the specified flow. - - Returns: - Callable[[~.CreatePageRequest], - Awaitable[~.Page]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_page' not in self._stubs: - self._stubs['create_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Pages/CreatePage', - request_serializer=gcdc_page.CreatePageRequest.serialize, - response_deserializer=gcdc_page.Page.deserialize, - ) - return self._stubs['create_page'] - - @property - def update_page(self) -> Callable[ - [gcdc_page.UpdatePageRequest], - Awaitable[gcdc_page.Page]]: - r"""Return a callable for the update page method over gRPC. - - Updates the specified page. - - Returns: - Callable[[~.UpdatePageRequest], - Awaitable[~.Page]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_page' not in self._stubs: - self._stubs['update_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Pages/UpdatePage', - request_serializer=gcdc_page.UpdatePageRequest.serialize, - response_deserializer=gcdc_page.Page.deserialize, - ) - return self._stubs['update_page'] - - @property - def delete_page(self) -> Callable[ - [page.DeletePageRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete page method over gRPC. - - Deletes the specified page. - - Returns: - Callable[[~.DeletePageRequest], - 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_page' not in self._stubs: - self._stubs['delete_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Pages/DeletePage', - request_serializer=page.DeletePageRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_page'] - - -__all__ = ( - 'PagesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py deleted file mode 100644 index 292d96e7..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/__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 SecuritySettingsServiceClient -from .async_client import SecuritySettingsServiceAsyncClient - -__all__ = ( - 'SecuritySettingsServiceClient', - 'SecuritySettingsServiceAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.py deleted file mode 100644 index 54b7d269..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/async_client.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. -# -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.dialogflowcx_v3.services.security_settings_service import pagers -from google.cloud.dialogflowcx_v3.types import security_settings -from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport -from .client import SecuritySettingsServiceClient - - -class SecuritySettingsServiceAsyncClient: - """Service for managing security settings for Dialogflow.""" - - _client: SecuritySettingsServiceClient - - DEFAULT_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_MTLS_ENDPOINT - - security_settings_path = staticmethod(SecuritySettingsServiceClient.security_settings_path) - parse_security_settings_path = staticmethod(SecuritySettingsServiceClient.parse_security_settings_path) - common_billing_account_path = staticmethod(SecuritySettingsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecuritySettingsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecuritySettingsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SecuritySettingsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SecuritySettingsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SecuritySettingsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SecuritySettingsServiceClient.common_project_path) - parse_common_project_path = staticmethod(SecuritySettingsServiceClient.parse_common_project_path) - common_location_path = staticmethod(SecuritySettingsServiceClient.common_location_path) - parse_common_location_path = staticmethod(SecuritySettingsServiceClient.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: - SecuritySettingsServiceAsyncClient: The constructed client. - """ - return SecuritySettingsServiceClient.from_service_account_info.__func__(SecuritySettingsServiceAsyncClient, 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: - SecuritySettingsServiceAsyncClient: The constructed client. - """ - return SecuritySettingsServiceClient.from_service_account_file.__func__(SecuritySettingsServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SecuritySettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SecuritySettingsServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SecuritySettingsServiceClient).get_transport_class, type(SecuritySettingsServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SecuritySettingsServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security settings service 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, ~.SecuritySettingsServiceTransport]): 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 = SecuritySettingsServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_security_settings(self, - request: gcdc_security_settings.CreateSecuritySettingsRequest = None, - *, - parent: str = None, - security_settings: gcdc_security_settings.SecuritySettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_security_settings.SecuritySettings: - r"""Create security settings in the specified location. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest`): - The request object. The request message for - [SecuritySettings.CreateSecuritySettings][]. - parent (:class:`str`): - Required. The location to create an - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] - for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - security_settings (:class:`google.cloud.dialogflowcx_v3.types.SecuritySettings`): - Required. The security settings to - create. - - This corresponds to the ``security_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, security_settings]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_security_settings.CreateSecuritySettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if security_settings is not None: - request.security_settings = security_settings - - # 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_security_settings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_security_settings(self, - request: security_settings.GetSecuritySettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> security_settings.SecuritySettings: - r"""Retrieves the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - The returned settings may be stale by up to 1 minute. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest`): - The request object. The request message for - [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings]. - name (:class:`str`): - Required. Resource name of the settings. Format: - ``projects//locations//securitySettings/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = security_settings.GetSecuritySettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_security_settings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_security_settings(self, - request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, - *, - security_settings: gcdc_security_settings.SecuritySettings = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_security_settings.SecuritySettings: - r"""Updates the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest`): - The request object. The request message for - [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. - security_settings (:class:`google.cloud.dialogflowcx_v3.types.SecuritySettings`): - Required. [SecuritySettings] object that contains values - for each of the fields to update. - - This corresponds to the ``security_settings`` 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.dialogflowcx_v3.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_settings, 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 = gcdc_security_settings.UpdateSecuritySettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_settings is not None: - request.security_settings = security_settings - if update_mask is not None: - 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_security_settings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_settings.name", request.security_settings.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_security_settings(self, - request: security_settings.ListSecuritySettingsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSecuritySettingsAsyncPager: - r"""Returns the list of all security settings in the - specified location. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest`): - The request object. The request message for - [SecuritySettings.ListSecuritySettings][]. - parent (:class:`str`): - Required. The location to list all security settings - 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.dialogflowcx_v3.services.security_settings_service.pagers.ListSecuritySettingsAsyncPager: - The response message for - [SecuritySettings.ListSecuritySettings][]. - - 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 = security_settings.ListSecuritySettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_security_settings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListSecuritySettingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_security_settings(self, - request: security_settings.DeleteSecuritySettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest`): - The request object. The request message for - [SecuritySettings.DeleteSecuritySettings][]. - name (:class:`str`): - Required. The name of the - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] - to delete. Format: - ``projects//locations//securitySettings/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = security_settings.DeleteSecuritySettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_security_settings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SecuritySettingsServiceAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py deleted file mode 100644 index e2583540..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/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 -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.dialogflowcx_v3.services.security_settings_service import pagers -from google.cloud.dialogflowcx_v3.types import security_settings -from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecuritySettingsServiceGrpcTransport -from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport - - -class SecuritySettingsServiceClientMeta(type): - """Metaclass for the SecuritySettingsService 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[SecuritySettingsServiceTransport]] - _transport_registry["grpc"] = SecuritySettingsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SecuritySettingsServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SecuritySettingsServiceTransport]: - """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 SecuritySettingsServiceClient(metaclass=SecuritySettingsServiceClientMeta): - """Service for managing security settings for Dialogflow.""" - - @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: - SecuritySettingsServiceClient: 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: - SecuritySettingsServiceClient: 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) -> SecuritySettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SecuritySettingsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def security_settings_path(project: str,location: str,security_settings: str,) -> str: - """Returns a fully-qualified security_settings string.""" - return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - - @staticmethod - def parse_security_settings_path(path: str) -> Dict[str,str]: - """Parses a security_settings path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def 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, SecuritySettingsServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security settings service 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, SecuritySettingsServiceTransport]): 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, SecuritySettingsServiceTransport): - # transport is a SecuritySettingsServiceTransport 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_security_settings(self, - request: gcdc_security_settings.CreateSecuritySettingsRequest = None, - *, - parent: str = None, - security_settings: gcdc_security_settings.SecuritySettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_security_settings.SecuritySettings: - r"""Create security settings in the specified location. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateSecuritySettingsRequest): - The request object. The request message for - [SecuritySettings.CreateSecuritySettings][]. - parent (str): - Required. The location to create an - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] - for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): - Required. The security settings to - create. - - This corresponds to the ``security_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, security_settings]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_security_settings.CreateSecuritySettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_security_settings.CreateSecuritySettingsRequest): - request = gcdc_security_settings.CreateSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if security_settings is not None: - request.security_settings = security_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_security_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_security_settings(self, - request: security_settings.GetSecuritySettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> security_settings.SecuritySettings: - r"""Retrieves the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - The returned settings may be stale by up to 1 minute. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetSecuritySettingsRequest): - The request object. The request message for - [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings]. - name (str): - Required. Resource name of the settings. Format: - ``projects//locations//securitySettings/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 security_settings.GetSecuritySettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, security_settings.GetSecuritySettingsRequest): - request = security_settings.GetSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_security_settings] - - # Certain fields should be provided 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_security_settings(self, - request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, - *, - security_settings: gcdc_security_settings.SecuritySettings = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_security_settings.SecuritySettings: - r"""Updates the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateSecuritySettingsRequest): - The request object. The request message for - [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. - security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): - Required. [SecuritySettings] object that contains values - for each of the fields to update. - - This corresponds to the ``security_settings`` 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.dialogflowcx_v3.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_settings, 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 gcdc_security_settings.UpdateSecuritySettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_security_settings.UpdateSecuritySettingsRequest): - request = gcdc_security_settings.UpdateSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_settings is not None: - request.security_settings = security_settings - if update_mask is not None: - 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_security_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_settings.name", request.security_settings.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_security_settings(self, - request: security_settings.ListSecuritySettingsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSecuritySettingsPager: - r"""Returns the list of all security settings in the - specified location. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest): - The request object. The request message for - [SecuritySettings.ListSecuritySettings][]. - parent (str): - Required. The location to list all security settings - 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.dialogflowcx_v3.services.security_settings_service.pagers.ListSecuritySettingsPager: - The response message for - [SecuritySettings.ListSecuritySettings][]. - - 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 security_settings.ListSecuritySettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, security_settings.ListSecuritySettingsRequest): - request = security_settings.ListSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_security_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListSecuritySettingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_security_settings(self, - request: security_settings.DeleteSecuritySettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - - Args: - request (google.cloud.dialogflowcx_v3.types.DeleteSecuritySettingsRequest): - The request object. The request message for - [SecuritySettings.DeleteSecuritySettings][]. - name (str): - Required. The name of the - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] - to delete. Format: - ``projects//locations//securitySettings/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 security_settings.DeleteSecuritySettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, security_settings.DeleteSecuritySettingsRequest): - request = security_settings.DeleteSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_security_settings] - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SecuritySettingsServiceClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py deleted file mode 100644 index 2989d74d..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/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.dialogflowcx_v3.types import security_settings - - -class ListSecuritySettingsPager: - """A pager for iterating through ``list_security_settings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``security_settings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSecuritySettings`` requests and continue to iterate - through the ``security_settings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` - 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[..., security_settings.ListSecuritySettingsResponse], - request: security_settings.ListSecuritySettingsRequest, - response: security_settings.ListSecuritySettingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse): - 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 = security_settings.ListSecuritySettingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[security_settings.ListSecuritySettingsResponse]: - 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[security_settings.SecuritySettings]: - for page in self.pages: - yield from page.security_settings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSecuritySettingsAsyncPager: - """A pager for iterating through ``list_security_settings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``security_settings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSecuritySettings`` requests and continue to iterate - through the ``security_settings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse` - 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[security_settings.ListSecuritySettingsResponse]], - request: security_settings.ListSecuritySettingsRequest, - response: security_settings.ListSecuritySettingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListSecuritySettingsResponse): - 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 = security_settings.ListSecuritySettingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[security_settings.ListSecuritySettingsResponse]: - 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[security_settings.SecuritySettings]: - async def async_generator(): - async for page in self.pages: - for response in page.security_settings: - 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/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py deleted file mode 100644 index 116b7680..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/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 SecuritySettingsServiceTransport -from .grpc import SecuritySettingsServiceGrpcTransport -from .grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecuritySettingsServiceTransport]] -_transport_registry['grpc'] = SecuritySettingsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SecuritySettingsServiceGrpcAsyncIOTransport - -__all__ = ( - 'SecuritySettingsServiceTransport', - 'SecuritySettingsServiceGrpcTransport', - 'SecuritySettingsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/base.py deleted file mode 100644 index 8c6f4bcb..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/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.dialogflowcx_v3.types import security_settings -from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflowcx', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class SecuritySettingsServiceTransport(abc.ABC): - """Abstract transport class for SecuritySettingsService.""" - - 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_security_settings: gapic_v1.method.wrap_method( - self.create_security_settings, - default_timeout=None, - client_info=client_info, - ), - self.get_security_settings: gapic_v1.method.wrap_method( - self.get_security_settings, - default_timeout=None, - client_info=client_info, - ), - self.update_security_settings: gapic_v1.method.wrap_method( - self.update_security_settings, - default_timeout=None, - client_info=client_info, - ), - self.list_security_settings: gapic_v1.method.wrap_method( - self.list_security_settings, - default_timeout=None, - client_info=client_info, - ), - self.delete_security_settings: gapic_v1.method.wrap_method( - self.delete_security_settings, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def create_security_settings(self) -> Callable[ - [gcdc_security_settings.CreateSecuritySettingsRequest], - Union[ - gcdc_security_settings.SecuritySettings, - Awaitable[gcdc_security_settings.SecuritySettings] - ]]: - raise NotImplementedError() - - @property - def get_security_settings(self) -> Callable[ - [security_settings.GetSecuritySettingsRequest], - Union[ - security_settings.SecuritySettings, - Awaitable[security_settings.SecuritySettings] - ]]: - raise NotImplementedError() - - @property - def update_security_settings(self) -> Callable[ - [gcdc_security_settings.UpdateSecuritySettingsRequest], - Union[ - gcdc_security_settings.SecuritySettings, - Awaitable[gcdc_security_settings.SecuritySettings] - ]]: - raise NotImplementedError() - - @property - def list_security_settings(self) -> Callable[ - [security_settings.ListSecuritySettingsRequest], - Union[ - security_settings.ListSecuritySettingsResponse, - Awaitable[security_settings.ListSecuritySettingsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_security_settings(self) -> Callable[ - [security_settings.DeleteSecuritySettingsRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'SecuritySettingsServiceTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py deleted file mode 100644 index 5c2f0f6a..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py +++ /dev/null @@ -1,359 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflowcx_v3.types import security_settings -from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings -from google.protobuf import empty_pb2 # type: ignore -from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO - - -class SecuritySettingsServiceGrpcTransport(SecuritySettingsServiceTransport): - """gRPC backend transport for SecuritySettingsService. - - Service for managing security settings for Dialogflow. - - 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_security_settings(self) -> Callable[ - [gcdc_security_settings.CreateSecuritySettingsRequest], - gcdc_security_settings.SecuritySettings]: - r"""Return a callable for the create security settings method over gRPC. - - Create security settings in the specified location. - - Returns: - Callable[[~.CreateSecuritySettingsRequest], - ~.SecuritySettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_settings' not in self._stubs: - self._stubs['create_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/CreateSecuritySettings', - request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, - response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, - ) - return self._stubs['create_security_settings'] - - @property - def get_security_settings(self) -> Callable[ - [security_settings.GetSecuritySettingsRequest], - security_settings.SecuritySettings]: - r"""Return a callable for the get security settings method over gRPC. - - Retrieves the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - The returned settings may be stale by up to 1 minute. - - Returns: - Callable[[~.GetSecuritySettingsRequest], - ~.SecuritySettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_security_settings' not in self._stubs: - self._stubs['get_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/GetSecuritySettings', - request_serializer=security_settings.GetSecuritySettingsRequest.serialize, - response_deserializer=security_settings.SecuritySettings.deserialize, - ) - return self._stubs['get_security_settings'] - - @property - def update_security_settings(self) -> Callable[ - [gcdc_security_settings.UpdateSecuritySettingsRequest], - gcdc_security_settings.SecuritySettings]: - r"""Return a callable for the update security settings method over gRPC. - - Updates the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - - Returns: - Callable[[~.UpdateSecuritySettingsRequest], - ~.SecuritySettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_settings' not in self._stubs: - self._stubs['update_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/UpdateSecuritySettings', - request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, - response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, - ) - return self._stubs['update_security_settings'] - - @property - def list_security_settings(self) -> Callable[ - [security_settings.ListSecuritySettingsRequest], - security_settings.ListSecuritySettingsResponse]: - r"""Return a callable for the list security settings method over gRPC. - - Returns the list of all security settings in the - specified location. - - Returns: - Callable[[~.ListSecuritySettingsRequest], - ~.ListSecuritySettingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_security_settings' not in self._stubs: - self._stubs['list_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/ListSecuritySettings', - request_serializer=security_settings.ListSecuritySettingsRequest.serialize, - response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, - ) - return self._stubs['list_security_settings'] - - @property - def delete_security_settings(self) -> Callable[ - [security_settings.DeleteSecuritySettingsRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete security settings method over gRPC. - - Deletes the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - - Returns: - Callable[[~.DeleteSecuritySettingsRequest], - ~.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_security_settings' not in self._stubs: - self._stubs['delete_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/DeleteSecuritySettings', - request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_security_settings'] - - -__all__ = ( - 'SecuritySettingsServiceGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py deleted file mode 100644 index bff5f4d6..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,363 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import security_settings -from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings -from google.protobuf import empty_pb2 # type: ignore -from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SecuritySettingsServiceGrpcTransport - - -class SecuritySettingsServiceGrpcAsyncIOTransport(SecuritySettingsServiceTransport): - """gRPC AsyncIO backend transport for SecuritySettingsService. - - Service for managing security settings for Dialogflow. - - 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_security_settings(self) -> Callable[ - [gcdc_security_settings.CreateSecuritySettingsRequest], - Awaitable[gcdc_security_settings.SecuritySettings]]: - r"""Return a callable for the create security settings method over gRPC. - - Create security settings in the specified location. - - Returns: - Callable[[~.CreateSecuritySettingsRequest], - Awaitable[~.SecuritySettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_settings' not in self._stubs: - self._stubs['create_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/CreateSecuritySettings', - request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, - response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, - ) - return self._stubs['create_security_settings'] - - @property - def get_security_settings(self) -> Callable[ - [security_settings.GetSecuritySettingsRequest], - Awaitable[security_settings.SecuritySettings]]: - r"""Return a callable for the get security settings method over gRPC. - - Retrieves the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - The returned settings may be stale by up to 1 minute. - - Returns: - Callable[[~.GetSecuritySettingsRequest], - Awaitable[~.SecuritySettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_security_settings' not in self._stubs: - self._stubs['get_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/GetSecuritySettings', - request_serializer=security_settings.GetSecuritySettingsRequest.serialize, - response_deserializer=security_settings.SecuritySettings.deserialize, - ) - return self._stubs['get_security_settings'] - - @property - def update_security_settings(self) -> Callable[ - [gcdc_security_settings.UpdateSecuritySettingsRequest], - Awaitable[gcdc_security_settings.SecuritySettings]]: - r"""Return a callable for the update security settings method over gRPC. - - Updates the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - - Returns: - Callable[[~.UpdateSecuritySettingsRequest], - Awaitable[~.SecuritySettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_settings' not in self._stubs: - self._stubs['update_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/UpdateSecuritySettings', - request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, - response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, - ) - return self._stubs['update_security_settings'] - - @property - def list_security_settings(self) -> Callable[ - [security_settings.ListSecuritySettingsRequest], - Awaitable[security_settings.ListSecuritySettingsResponse]]: - r"""Return a callable for the list security settings method over gRPC. - - Returns the list of all security settings in the - specified location. - - Returns: - Callable[[~.ListSecuritySettingsRequest], - Awaitable[~.ListSecuritySettingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_security_settings' not in self._stubs: - self._stubs['list_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/ListSecuritySettings', - request_serializer=security_settings.ListSecuritySettingsRequest.serialize, - response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, - ) - return self._stubs['list_security_settings'] - - @property - def delete_security_settings(self) -> Callable[ - [security_settings.DeleteSecuritySettingsRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete security settings method over gRPC. - - Deletes the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings]. - - Returns: - Callable[[~.DeleteSecuritySettingsRequest], - 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_security_settings' not in self._stubs: - self._stubs['delete_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.SecuritySettingsService/DeleteSecuritySettings', - request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_security_settings'] - - -__all__ = ( - 'SecuritySettingsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py deleted file mode 100644 index fb6678b1..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py deleted file mode 100644 index d58bcc80..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/async_client.py +++ /dev/null @@ -1,632 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.session_entity_types import pagers -from google.cloud.dialogflowcx_v3.types import entity_type -from google.cloud.dialogflowcx_v3.types import session_entity_type -from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_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.cx.v3.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. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest`): - The request object. The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. - parent (:class:`str`): - Required. The session to list all session entity types - from. Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager: - The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.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. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest`): - The request object. The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType]. - name (:class:`str`): - Required. The name of the session entity type. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3.EntityType] at - the user session level (we refer to the entity types - defined at the agent level as "custom entity types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not 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: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, - *, - parent: str = None, - session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_session_entity_type.SessionEntityType: - r"""Creates a session entity type. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest`): - The request object. The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType]. - parent (:class:`str`): - Required. The session to create a session entity type - for. Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - 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.dialogflowcx_v3.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.dialogflowcx_v3.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3.EntityType] at - the user session level (we refer to the entity types - defined at the agent level as "custom entity types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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, 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 = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if session_entity_type is not None: - 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: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, - *, - session_entity_type: gcdc_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]] = (), - ) -> gcdc_session_entity_type.SessionEntityType: - r"""Updates the specified session entity type. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest`): - The request object. The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType]. - session_entity_type (:class:`google.cloud.dialogflowcx_v3.types.SessionEntityType`): - Required. The session entity type to update. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - 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`): - 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.dialogflowcx_v3.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3.EntityType] at - the user session level (we refer to the entity types - defined at the agent level as "custom entity types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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([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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if session_entity_type is not None: - request.session_entity_type = session_entity_type - if update_mask is not None: - 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. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest`): - The request object. The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType]. - name (:class:`str`): - Required. The name of the session entity type to delete. - Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SessionEntityTypesAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py deleted file mode 100644 index 8d15234d..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py +++ /dev/null @@ -1,819 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.session_entity_types import pagers -from google.cloud.dialogflowcx_v3.types import entity_type -from google.cloud.dialogflowcx_v3.types import session_entity_type -from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_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.cx.v3.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,location: str,agent: str,session: str,entity_type: str,) -> str: - """Returns a fully-qualified session_entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, 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.+?)/locations/(?P.+?)/agents/(?P.+?)/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. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListSessionEntityTypesRequest): - The request object. The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. - parent (str): - Required. The session to list all session entity types - from. Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.session_entity_types.pagers.ListSessionEntityTypesPager: - The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.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. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.GetSessionEntityType]. - name (str): - Required. The name of the session entity type. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3.EntityType] at - the user session level (we refer to the entity types - defined at the agent level as "custom entity types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is 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: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, - *, - parent: str = None, - session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_session_entity_type.SessionEntityType: - r"""Creates a session entity type. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType]. - parent (str): - Required. The session to create a session entity type - for. Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - session_entity_type (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3.EntityType] at - the user session level (we refer to the entity types - defined at the agent level as "custom entity types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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, 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 gcdc_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, gcdc_session_entity_type.CreateSessionEntityTypeRequest): - request = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if session_entity_type is not None: - 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: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, - *, - session_entity_type: gcdc_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]] = (), - ) -> gcdc_session_entity_type.SessionEntityType: - r"""Updates the specified session entity type. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.UpdateSessionEntityType]. - session_entity_type (google.cloud.dialogflowcx_v3.types.SessionEntityType): - Required. The session entity type to update. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - 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): - 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.dialogflowcx_v3.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3.EntityType] at - the user session level (we refer to the entity types - defined at the agent level as "custom entity types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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([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 gcdc_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, gcdc_session_entity_type.UpdateSessionEntityTypeRequest): - request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if session_entity_type is not None: - request.session_entity_type = session_entity_type - if update_mask is not None: - 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. - - Args: - request (google.cloud.dialogflowcx_v3.types.DeleteSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.DeleteSessionEntityType]. - name (str): - Required. The name of the session entity type to delete. - Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SessionEntityTypesClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py deleted file mode 100644 index 89fb79e7..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListSessionEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListSessionEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.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/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py deleted file mode 100644 index fee52672..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/base.py deleted file mode 100644 index 4c384e5b..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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.dialogflowcx_v3.types import session_entity_type -from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflowcx', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -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[ - [gcdc_session_entity_type.CreateSessionEntityTypeRequest], - Union[ - gcdc_session_entity_type.SessionEntityType, - Awaitable[gcdc_session_entity_type.SessionEntityType] - ]]: - raise NotImplementedError() - - @property - def update_session_entity_type(self) -> Callable[ - [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], - Union[ - gcdc_session_entity_type.SessionEntityType, - Awaitable[gcdc_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/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py deleted file mode 100644 index 10d2c22f..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/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.dialogflowcx_v3.types import session_entity_type -from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type -from google.protobuf import empty_pb2 # type: ignore -from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO - - -class SessionEntityTypesGrpcTransport(SessionEntityTypesTransport): - """gRPC backend transport for SessionEntityTypes. - - Service for managing - [SessionEntityTypes][google.cloud.dialogflow.cx.v3.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. - - 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.cx.v3.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. - - 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.cx.v3.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[ - [gcdc_session_entity_type.CreateSessionEntityTypeRequest], - gcdc_session_entity_type.SessionEntityType]: - r"""Return a callable for the create session entity type method over gRPC. - - Creates a session entity type. - - 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.cx.v3.SessionEntityTypes/CreateSessionEntityType', - request_serializer=gcdc_session_entity_type.CreateSessionEntityTypeRequest.serialize, - response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['create_session_entity_type'] - - @property - def update_session_entity_type(self) -> Callable[ - [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], - gcdc_session_entity_type.SessionEntityType]: - r"""Return a callable for the update session entity type method over gRPC. - - Updates the specified session entity type. - - 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.cx.v3.SessionEntityTypes/UpdateSessionEntityType', - request_serializer=gcdc_session_entity_type.UpdateSessionEntityTypeRequest.serialize, - response_deserializer=gcdc_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. - - 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.cx.v3.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/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc_asyncio.py deleted file mode 100644 index e70c7923..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/session_entity_types/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.dialogflowcx_v3.types import session_entity_type -from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type -from google.protobuf import empty_pb2 # 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.cx.v3.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. - - 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.cx.v3.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. - - 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.cx.v3.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[ - [gcdc_session_entity_type.CreateSessionEntityTypeRequest], - Awaitable[gcdc_session_entity_type.SessionEntityType]]: - r"""Return a callable for the create session entity type method over gRPC. - - Creates a session entity type. - - 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.cx.v3.SessionEntityTypes/CreateSessionEntityType', - request_serializer=gcdc_session_entity_type.CreateSessionEntityTypeRequest.serialize, - response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['create_session_entity_type'] - - @property - def update_session_entity_type(self) -> Callable[ - [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], - Awaitable[gcdc_session_entity_type.SessionEntityType]]: - r"""Return a callable for the update session entity type method over gRPC. - - Updates the specified session entity type. - - 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.cx.v3.SessionEntityTypes/UpdateSessionEntityType', - request_serializer=gcdc_session_entity_type.UpdateSessionEntityTypeRequest.serialize, - response_deserializer=gcdc_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. - - 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.cx.v3.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/v3/google/cloud/dialogflowcx_v3/services/sessions/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/__init__.py deleted file mode 100644 index 92490cc5..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py deleted file mode 100644 index bde43b86..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/async_client.py +++ /dev/null @@ -1,460 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.types import audio_config -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import session -from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport -from .client import SessionsClient - - -class SessionsAsyncClient: - """A session represents an interaction with a user. You retrieve user - input and pass it to the - [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] - method to determine user intent and respond. - """ - - _client: SessionsClient - - DEFAULT_ENDPOINT = SessionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SessionsClient.DEFAULT_MTLS_ENDPOINT - - entity_type_path = staticmethod(SessionsClient.entity_type_path) - parse_entity_type_path = staticmethod(SessionsClient.parse_entity_type_path) - flow_path = staticmethod(SessionsClient.flow_path) - parse_flow_path = staticmethod(SessionsClient.parse_flow_path) - intent_path = staticmethod(SessionsClient.intent_path) - parse_intent_path = staticmethod(SessionsClient.parse_intent_path) - page_path = staticmethod(SessionsClient.page_path) - parse_page_path = staticmethod(SessionsClient.parse_page_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) - transition_route_group_path = staticmethod(SessionsClient.transition_route_group_path) - parse_transition_route_group_path = staticmethod(SessionsClient.parse_transition_route_group_path) - webhook_path = staticmethod(SessionsClient.webhook_path) - parse_webhook_path = staticmethod(SessionsClient.parse_webhook_path) - common_billing_account_path = staticmethod(SessionsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SessionsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SessionsClient.common_folder_path) - parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) - common_organization_path = staticmethod(SessionsClient.common_organization_path) - parse_common_organization_path = staticmethod(SessionsClient.parse_common_organization_path) - common_project_path = staticmethod(SessionsClient.common_project_path) - parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) - common_location_path = staticmethod(SessionsClient.common_location_path) - parse_common_location_path = staticmethod(SessionsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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: session.DetectIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> 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 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.dialogflowcx_v3.types.DetectIntentRequest`): - The request object. The request to detect user's intent. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.DetectIntentResponse: - The message returned from the - DetectIntent method. - - """ - # Create or coerce a protobuf request object. - request = session.DetectIntentRequest(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.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.dialogflowcx_v3.types.StreamingDetectIntentRequest`]): - The request object AsyncIterator. The top-level message sent by the - client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] - method. - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.output_audio_config]. - 2. If - [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio.config][google.cloud.dialogflow.cx.v3.AudioInput.config], - all subsequent messages must contain - [query_input.audio.audio][google.cloud.dialogflow.cx.v3.AudioInput.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.cx.v3.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.dialogflowcx_v3.types.StreamingDetectIntentResponse]: - The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. If enable_partial_response is true, the following - N messages (currently 1 <= N <= 4) contain - detect_intent_response. The first (N-1) - detect_intent_responses will have response_type - set to PARTIAL. The last detect_intent_response - has response_type set to FINAL. If response_type - is false, response stream only contains the final - detect_intent_response. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_detect_intent, - default_timeout=220.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def match_intent(self, - request: session.MatchIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session.MatchIntentResponse: - r"""Returns preliminary intent match results, doesn't - change the session status. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.MatchIntentRequest`): - The request object. Request of [MatchIntent][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.MatchIntentResponse: - Response of [MatchIntent][]. - """ - # Create or coerce a protobuf request object. - request = session.MatchIntentRequest(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.match_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(( - ("session", request.session), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def fulfill_intent(self, - request: session.FulfillIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session.FulfillIntentResponse: - r"""Fulfills a matched intent returned by - [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. - Must be called after - [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], - with input from - [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. - Otherwise, the behavior is undefined. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.FulfillIntentRequest`): - The request object. Request of [FulfillIntent][] - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.FulfillIntentResponse: - Response of [FulfillIntent][] - """ - # Create or coerce a protobuf request object. - request = session.FulfillIntentRequest(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.fulfill_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(( - ("match_intent_request.session", request.match_intent_request.session), - )), - ) - - # 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SessionsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/client.py deleted file mode 100644 index 9ac9dce3..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/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 -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.dialogflowcx_v3.types import audio_config -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import session -from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SessionsGrpcTransport -from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport - - -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 session represents an interaction with a user. You retrieve user - input and pass it to the - [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] - method to determine user intent and respond. - """ - - @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 entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: - """Returns a fully-qualified page string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - - @staticmethod - def parse_page_path(path: str) -> Dict[str,str]: - """Parses a page path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def session_path(project: str,location: str,agent: str,session: str,) -> str: - """Returns a fully-qualified session string.""" - return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format(project=project, location=location, agent=agent, session=session, ) - - @staticmethod - def parse_session_path(path: str) -> Dict[str,str]: - """Parses a session path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def session_entity_type_path(project: str,location: str,agent: str,session: str,entity_type: str,) -> str: - """Returns a fully-qualified session_entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, 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.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: - """Returns a fully-qualified transition_route_group string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - - @staticmethod - def parse_transition_route_group_path(path: str) -> Dict[str,str]: - """Parses a transition_route_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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: session.DetectIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> 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 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.dialogflowcx_v3.types.DetectIntentRequest): - The request object. The request to detect user's intent. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.DetectIntentResponse: - The message returned from the - DetectIntent method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a session.DetectIntentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, session.DetectIntentRequest): - request = session.DetectIntentRequest(request) - - # 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.dialogflowcx_v3.types.StreamingDetectIntentRequest]): - The request object iterator. The top-level message sent by the - client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] - method. - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.output_audio_config]. - 2. If - [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio.config][google.cloud.dialogflow.cx.v3.AudioInput.config], - all subsequent messages must contain - [query_input.audio.audio][google.cloud.dialogflow.cx.v3.AudioInput.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.cx.v3.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.dialogflowcx_v3.types.StreamingDetectIntentResponse]: - The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. If enable_partial_response is true, the following - N messages (currently 1 <= N <= 4) contain - detect_intent_response. The first (N-1) - detect_intent_responses will have response_type - set to PARTIAL. The last detect_intent_response - has response_type set to FINAL. If response_type - is false, response stream only contains the final - detect_intent_response. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.streaming_detect_intent] - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def match_intent(self, - request: session.MatchIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session.MatchIntentResponse: - r"""Returns preliminary intent match results, doesn't - change the session status. - - Args: - request (google.cloud.dialogflowcx_v3.types.MatchIntentRequest): - The request object. Request of [MatchIntent][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.MatchIntentResponse: - Response of [MatchIntent][]. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a session.MatchIntentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, session.MatchIntentRequest): - request = session.MatchIntentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.match_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 fulfill_intent(self, - request: session.FulfillIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session.FulfillIntentResponse: - r"""Fulfills a matched intent returned by - [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. - Must be called after - [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], - with input from - [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. - Otherwise, the behavior is undefined. - - Args: - request (google.cloud.dialogflowcx_v3.types.FulfillIntentRequest): - The request object. Request of [FulfillIntent][] - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.FulfillIntentResponse: - Response of [FulfillIntent][] - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a session.FulfillIntentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, session.FulfillIntentRequest): - request = session.FulfillIntentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.fulfill_intent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("match_intent_request.session", request.match_intent_request.session), - )), - ) - - # 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SessionsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py deleted file mode 100644 index fde19f61..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/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/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py deleted file mode 100644 index f5765860..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py +++ /dev/null @@ -1,231 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import session - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflowcx', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -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, - ), - self.match_intent: gapic_v1.method.wrap_method( - self.match_intent, - default_timeout=None, - client_info=client_info, - ), - self.fulfill_intent: gapic_v1.method.wrap_method( - self.fulfill_intent, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def detect_intent(self) -> Callable[ - [session.DetectIntentRequest], - Union[ - session.DetectIntentResponse, - Awaitable[session.DetectIntentResponse] - ]]: - raise NotImplementedError() - - @property - def streaming_detect_intent(self) -> Callable[ - [session.StreamingDetectIntentRequest], - Union[ - session.StreamingDetectIntentResponse, - Awaitable[session.StreamingDetectIntentResponse] - ]]: - raise NotImplementedError() - - @property - def match_intent(self) -> Callable[ - [session.MatchIntentRequest], - Union[ - session.MatchIntentResponse, - Awaitable[session.MatchIntentResponse] - ]]: - raise NotImplementedError() - - @property - def fulfill_intent(self) -> Callable[ - [session.FulfillIntentRequest], - Union[ - session.FulfillIntentResponse, - Awaitable[session.FulfillIntentResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'SessionsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py deleted file mode 100644 index 39238871..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.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 warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflowcx_v3.types import session -from .base import SessionsTransport, DEFAULT_CLIENT_INFO - - -class SessionsGrpcTransport(SessionsTransport): - """gRPC backend transport for Sessions. - - A session represents an interaction with a user. You retrieve user - input and pass it to the - [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] - method to determine user intent and respond. - - 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[ - [session.DetectIntentRequest], - 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 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.cx.v3.Sessions/DetectIntent', - request_serializer=session.DetectIntentRequest.serialize, - response_deserializer=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.cx.v3.Sessions/StreamingDetectIntent', - request_serializer=session.StreamingDetectIntentRequest.serialize, - response_deserializer=session.StreamingDetectIntentResponse.deserialize, - ) - return self._stubs['streaming_detect_intent'] - - @property - def match_intent(self) -> Callable[ - [session.MatchIntentRequest], - session.MatchIntentResponse]: - r"""Return a callable for the match intent method over gRPC. - - Returns preliminary intent match results, doesn't - change the session status. - - Returns: - Callable[[~.MatchIntentRequest], - ~.MatchIntentResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'match_intent' not in self._stubs: - self._stubs['match_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Sessions/MatchIntent', - request_serializer=session.MatchIntentRequest.serialize, - response_deserializer=session.MatchIntentResponse.deserialize, - ) - return self._stubs['match_intent'] - - @property - def fulfill_intent(self) -> Callable[ - [session.FulfillIntentRequest], - session.FulfillIntentResponse]: - r"""Return a callable for the fulfill intent method over gRPC. - - Fulfills a matched intent returned by - [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. - Must be called after - [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], - with input from - [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. - Otherwise, the behavior is undefined. - - Returns: - Callable[[~.FulfillIntentRequest], - ~.FulfillIntentResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fulfill_intent' not in self._stubs: - self._stubs['fulfill_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Sessions/FulfillIntent', - request_serializer=session.FulfillIntentRequest.serialize, - response_deserializer=session.FulfillIntentResponse.deserialize, - ) - return self._stubs['fulfill_intent'] - - -__all__ = ( - 'SessionsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py deleted file mode 100644 index 7341f960..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py +++ /dev/null @@ -1,354 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import session -from .base import SessionsTransport, DEFAULT_CLIENT_INFO -from .grpc import SessionsGrpcTransport - - -class SessionsGrpcAsyncIOTransport(SessionsTransport): - """gRPC AsyncIO backend transport for Sessions. - - A session represents an interaction with a user. You retrieve user - input and pass it to the - [DetectIntent][google.cloud.dialogflow.cx.v3.Sessions.DetectIntent] - method to determine user intent and respond. - - 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[ - [session.DetectIntentRequest], - Awaitable[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 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.cx.v3.Sessions/DetectIntent', - request_serializer=session.DetectIntentRequest.serialize, - response_deserializer=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.cx.v3.Sessions/StreamingDetectIntent', - request_serializer=session.StreamingDetectIntentRequest.serialize, - response_deserializer=session.StreamingDetectIntentResponse.deserialize, - ) - return self._stubs['streaming_detect_intent'] - - @property - def match_intent(self) -> Callable[ - [session.MatchIntentRequest], - Awaitable[session.MatchIntentResponse]]: - r"""Return a callable for the match intent method over gRPC. - - Returns preliminary intent match results, doesn't - change the session status. - - Returns: - Callable[[~.MatchIntentRequest], - Awaitable[~.MatchIntentResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'match_intent' not in self._stubs: - self._stubs['match_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Sessions/MatchIntent', - request_serializer=session.MatchIntentRequest.serialize, - response_deserializer=session.MatchIntentResponse.deserialize, - ) - return self._stubs['match_intent'] - - @property - def fulfill_intent(self) -> Callable[ - [session.FulfillIntentRequest], - Awaitable[session.FulfillIntentResponse]]: - r"""Return a callable for the fulfill intent method over gRPC. - - Fulfills a matched intent returned by - [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent]. - Must be called after - [MatchIntent][google.cloud.dialogflow.cx.v3.Sessions.MatchIntent], - with input from - [MatchIntentResponse][google.cloud.dialogflow.cx.v3.MatchIntentResponse]. - Otherwise, the behavior is undefined. - - Returns: - Callable[[~.FulfillIntentRequest], - Awaitable[~.FulfillIntentResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fulfill_intent' not in self._stubs: - self._stubs['fulfill_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Sessions/FulfillIntent', - request_serializer=session.FulfillIntentRequest.serialize, - response_deserializer=session.FulfillIntentResponse.deserialize, - ) - return self._stubs['fulfill_intent'] - - -__all__ = ( - 'SessionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py deleted file mode 100644 index 938c210f..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/__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 TestCasesClient -from .async_client import TestCasesAsyncClient - -__all__ = ( - 'TestCasesClient', - 'TestCasesAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py deleted file mode 100644 index 77cf5892..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py +++ /dev/null @@ -1,1073 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.test_cases import pagers -from google.cloud.dialogflowcx_v3.types import test_case -from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport -from .client import TestCasesClient - - -class TestCasesAsyncClient: - """Service for managing [Test - Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case - Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. - """ - - _client: TestCasesClient - - DEFAULT_ENDPOINT = TestCasesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TestCasesClient.DEFAULT_MTLS_ENDPOINT - - agent_path = staticmethod(TestCasesClient.agent_path) - parse_agent_path = staticmethod(TestCasesClient.parse_agent_path) - entity_type_path = staticmethod(TestCasesClient.entity_type_path) - parse_entity_type_path = staticmethod(TestCasesClient.parse_entity_type_path) - environment_path = staticmethod(TestCasesClient.environment_path) - parse_environment_path = staticmethod(TestCasesClient.parse_environment_path) - flow_path = staticmethod(TestCasesClient.flow_path) - parse_flow_path = staticmethod(TestCasesClient.parse_flow_path) - intent_path = staticmethod(TestCasesClient.intent_path) - parse_intent_path = staticmethod(TestCasesClient.parse_intent_path) - page_path = staticmethod(TestCasesClient.page_path) - parse_page_path = staticmethod(TestCasesClient.parse_page_path) - test_case_path = staticmethod(TestCasesClient.test_case_path) - parse_test_case_path = staticmethod(TestCasesClient.parse_test_case_path) - test_case_result_path = staticmethod(TestCasesClient.test_case_result_path) - parse_test_case_result_path = staticmethod(TestCasesClient.parse_test_case_result_path) - transition_route_group_path = staticmethod(TestCasesClient.transition_route_group_path) - parse_transition_route_group_path = staticmethod(TestCasesClient.parse_transition_route_group_path) - webhook_path = staticmethod(TestCasesClient.webhook_path) - parse_webhook_path = staticmethod(TestCasesClient.parse_webhook_path) - common_billing_account_path = staticmethod(TestCasesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TestCasesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TestCasesClient.common_folder_path) - parse_common_folder_path = staticmethod(TestCasesClient.parse_common_folder_path) - common_organization_path = staticmethod(TestCasesClient.common_organization_path) - parse_common_organization_path = staticmethod(TestCasesClient.parse_common_organization_path) - common_project_path = staticmethod(TestCasesClient.common_project_path) - parse_common_project_path = staticmethod(TestCasesClient.parse_common_project_path) - common_location_path = staticmethod(TestCasesClient.common_location_path) - parse_common_location_path = staticmethod(TestCasesClient.parse_common_location_path) - - @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: - TestCasesAsyncClient: The constructed client. - """ - return TestCasesClient.from_service_account_info.__func__(TestCasesAsyncClient, 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: - TestCasesAsyncClient: The constructed client. - """ - return TestCasesClient.from_service_account_file.__func__(TestCasesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> TestCasesTransport: - """Returns the transport used by the client instance. - - Returns: - TestCasesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(TestCasesClient).get_transport_class, type(TestCasesClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, TestCasesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the test cases 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, ~.TestCasesTransport]): 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 = TestCasesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_test_cases(self, - request: test_case.ListTestCasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTestCasesAsyncPager: - r"""Fetches a list of test cases for a given agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListTestCasesRequest`): - The request object. The request message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. - parent (:class:`str`): - Required. The agent to list all pages for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCasesAsyncPager: - The response message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. - - 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 = test_case.ListTestCasesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_test_cases, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListTestCasesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_delete_test_cases(self, - request: test_case.BatchDeleteTestCasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Batch deletes test cases. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest`): - The request object. The request message for - [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases]. - parent (:class:`str`): - Required. The agent to delete test cases from. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = test_case.BatchDeleteTestCasesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_test_cases, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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 get_test_case(self, - request: test_case.GetTestCaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.TestCase: - r"""Gets a test case. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetTestCaseRequest`): - The request object. The request message for - [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3.TestCases.GetTestCase]. - name (:class:`str`): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = test_case.GetTestCaseRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_test_case, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_test_case(self, - request: gcdc_test_case.CreateTestCaseRequest = None, - *, - parent: str = None, - test_case: gcdc_test_case.TestCase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_test_case.TestCase: - r"""Creates a test case for the given agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest`): - The request object. The request message for - [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase]. - parent (:class:`str`): - Required. The agent to create the test case for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - test_case (:class:`google.cloud.dialogflowcx_v3.types.TestCase`): - Required. The test case to create. - This corresponds to the ``test_case`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, test_case]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_test_case.CreateTestCaseRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if test_case is not None: - request.test_case = test_case - - # 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_test_case, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_test_case(self, - request: gcdc_test_case.UpdateTestCaseRequest = None, - *, - test_case: gcdc_test_case.TestCase = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_test_case.TestCase: - r"""Updates the specified test case. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest`): - The request object. The request message for - [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase]. - test_case (:class:`google.cloud.dialogflowcx_v3.types.TestCase`): - Required. The test case to update. - This corresponds to the ``test_case`` 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 should be - updated. The - [``creationTime``][google.cloud.dialogflow.cx.v3.TestCase.creation_time] - and - [``lastTestResult``][google.cloud.dialogflow.cx.v3.TestCase.last_test_result] - cannot 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.dialogflowcx_v3.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([test_case, 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 = gcdc_test_case.UpdateTestCaseRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if test_case is not None: - request.test_case = test_case - if update_mask is not None: - 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_test_case, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("test_case.name", request.test_case.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_test_case(self, - request: test_case.RunTestCaseRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Kicks off a test case run. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.RunTestCaseRequest`): - The request object. The request message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.RunTestCaseResponse` - The response message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. - - """ - # Create or coerce a protobuf request object. - request = test_case.RunTestCaseRequest(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.run_test_case, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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, - test_case.RunTestCaseResponse, - metadata_type=test_case.RunTestCaseMetadata, - ) - - # Done; return the response. - return response - - async def batch_run_test_cases(self, - request: test_case.BatchRunTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Kicks off a batch run of test cases. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest`): - The request object. The request message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesResponse` - The response message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. - - """ - # Create or coerce a protobuf request object. - request = test_case.BatchRunTestCasesRequest(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_run_test_cases, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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, - test_case.BatchRunTestCasesResponse, - metadata_type=test_case.BatchRunTestCasesMetadata, - ) - - # Done; return the response. - return response - - async def calculate_coverage(self, - request: test_case.CalculateCoverageRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.CalculateCoverageResponse: - r"""Calculates the test coverage for an agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest`): - The request object. The request message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.CalculateCoverageResponse: - The response message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. - - """ - # Create or coerce a protobuf request object. - request = test_case.CalculateCoverageRequest(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.calculate_coverage, - default_timeout=None, - client_info=DEFAULT_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", request.agent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_test_cases(self, - request: test_case.ImportTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest`): - The request object. The request message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesResponse` - The response message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. - - """ - # Create or coerce a protobuf request object. - request = test_case.ImportTestCasesRequest(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_test_cases, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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, - test_case.ImportTestCasesResponse, - metadata_type=test_case.ImportTestCasesMetadata, - ) - - # Done; return the response. - return response - - async def export_test_cases(self, - request: test_case.ExportTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest`): - The request object. The request message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesResponse` - The response message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. - - """ - # Create or coerce a protobuf request object. - request = test_case.ExportTestCasesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_test_cases, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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, - test_case.ExportTestCasesResponse, - metadata_type=test_case.ExportTestCasesMetadata, - ) - - # Done; return the response. - return response - - async def list_test_case_results(self, - request: test_case.ListTestCaseResultsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTestCaseResultsAsyncPager: - r"""Fetches a list of results for a given test case. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest`): - The request object. The request message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. - parent (:class:`str`): - Required. The test case to list results for. Format: - ``projects//locations//agents// testCases/``. - Specify a ``-`` as a wildcard for TestCase ID to list - results across multiple test cases. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCaseResultsAsyncPager: - The response message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. - - 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 = test_case.ListTestCaseResultsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_test_case_results, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListTestCaseResultsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_test_case_result(self, - request: test_case.GetTestCaseResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.TestCaseResult: - r"""Gets a test case result. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest`): - The request object. The request message for - [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. - name (:class:`str`): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases//results/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.TestCaseResult: - Represents a result from running a - test case in an agent environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = test_case.GetTestCaseResultRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_test_case_result, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "TestCasesAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py deleted file mode 100644 index 4f2ae94d..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/client.py +++ /dev/null @@ -1,1346 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.test_cases import pagers -from google.cloud.dialogflowcx_v3.types import test_case -from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TestCasesGrpcTransport -from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport - - -class TestCasesClientMeta(type): - """Metaclass for the TestCases 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[TestCasesTransport]] - _transport_registry["grpc"] = TestCasesGrpcTransport - _transport_registry["grpc_asyncio"] = TestCasesGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[TestCasesTransport]: - """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 TestCasesClient(metaclass=TestCasesClientMeta): - """Service for managing [Test - Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case - Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. - """ - - @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: - TestCasesClient: 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: - TestCasesClient: 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) -> TestCasesTransport: - """Returns the transport used by the client instance. - - Returns: - TestCasesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def agent_path(project: str,location: str,agent: str,) -> str: - """Returns a fully-qualified agent string.""" - return "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) - - @staticmethod - def parse_agent_path(path: str) -> Dict[str,str]: - """Parses a agent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def environment_path(project: str,location: str,agent: str,environment: str,) -> str: - """Returns a fully-qualified environment string.""" - return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - - @staticmethod - def parse_environment_path(path: str) -> Dict[str,str]: - """Parses a environment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: - """Returns a fully-qualified page string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - - @staticmethod - def parse_page_path(path: str) -> Dict[str,str]: - """Parses a page path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def test_case_path(project: str,location: str,agent: str,test_case: str,) -> str: - """Returns a fully-qualified test_case string.""" - return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(project=project, location=location, agent=agent, test_case=test_case, ) - - @staticmethod - def parse_test_case_path(path: str) -> Dict[str,str]: - """Parses a test_case path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def test_case_result_path(project: str,location: str,agent: str,test_case: str,result: str,) -> str: - """Returns a fully-qualified test_case_result string.""" - return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) - - @staticmethod - def parse_test_case_result_path(path: str) -> Dict[str,str]: - """Parses a test_case_result path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: - """Returns a fully-qualified transition_route_group string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - - @staticmethod - def parse_transition_route_group_path(path: str) -> Dict[str,str]: - """Parses a transition_route_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, TestCasesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the test cases 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, TestCasesTransport]): 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, TestCasesTransport): - # transport is a TestCasesTransport 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_test_cases(self, - request: test_case.ListTestCasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTestCasesPager: - r"""Fetches a list of test cases for a given agent. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListTestCasesRequest): - The request object. The request message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. - parent (str): - Required. The agent to list all pages for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCasesPager: - The response message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. - - 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 test_case.ListTestCasesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.ListTestCasesRequest): - request = test_case.ListTestCasesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_test_cases] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListTestCasesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_delete_test_cases(self, - request: test_case.BatchDeleteTestCasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Batch deletes test cases. - - Args: - request (google.cloud.dialogflowcx_v3.types.BatchDeleteTestCasesRequest): - The request object. The request message for - [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases]. - parent (str): - Required. The agent to delete test cases from. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 test_case.BatchDeleteTestCasesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.BatchDeleteTestCasesRequest): - request = test_case.BatchDeleteTestCasesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_delete_test_cases] - - # Certain fields should be 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 get_test_case(self, - request: test_case.GetTestCaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.TestCase: - r"""Gets a test case. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetTestCaseRequest): - The request object. The request message for - [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3.TestCases.GetTestCase]. - name (str): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a test_case.GetTestCaseRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.GetTestCaseRequest): - request = test_case.GetTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_test_case] - - # Certain fields should be provided 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_test_case(self, - request: gcdc_test_case.CreateTestCaseRequest = None, - *, - parent: str = None, - test_case: gcdc_test_case.TestCase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_test_case.TestCase: - r"""Creates a test case for the given agent. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateTestCaseRequest): - The request object. The request message for - [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase]. - parent (str): - Required. The agent to create the test case for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - test_case (google.cloud.dialogflowcx_v3.types.TestCase): - Required. The test case to create. - This corresponds to the ``test_case`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, test_case]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_test_case.CreateTestCaseRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_test_case.CreateTestCaseRequest): - request = gcdc_test_case.CreateTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if test_case is not None: - request.test_case = test_case - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_test_case] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_test_case(self, - request: gcdc_test_case.UpdateTestCaseRequest = None, - *, - test_case: gcdc_test_case.TestCase = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_test_case.TestCase: - r"""Updates the specified test case. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateTestCaseRequest): - The request object. The request message for - [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase]. - test_case (google.cloud.dialogflowcx_v3.types.TestCase): - Required. The test case to update. - This corresponds to the ``test_case`` 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 should be - updated. The - [``creationTime``][google.cloud.dialogflow.cx.v3.TestCase.creation_time] - and - [``lastTestResult``][google.cloud.dialogflow.cx.v3.TestCase.last_test_result] - cannot 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.dialogflowcx_v3.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([test_case, 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 gcdc_test_case.UpdateTestCaseRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_test_case.UpdateTestCaseRequest): - request = gcdc_test_case.UpdateTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if test_case is not None: - request.test_case = test_case - if update_mask is not None: - 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_test_case] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("test_case.name", request.test_case.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_test_case(self, - request: test_case.RunTestCaseRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Kicks off a test case run. - - Args: - request (google.cloud.dialogflowcx_v3.types.RunTestCaseRequest): - The request object. The request message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.RunTestCaseResponse` - The response message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a test_case.RunTestCaseRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.RunTestCaseRequest): - request = test_case.RunTestCaseRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_test_case] - - # Certain fields should be provided 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, - test_case.RunTestCaseResponse, - metadata_type=test_case.RunTestCaseMetadata, - ) - - # Done; return the response. - return response - - def batch_run_test_cases(self, - request: test_case.BatchRunTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Kicks off a batch run of test cases. - - Args: - request (google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest): - The request object. The request message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesResponse` - The response message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a test_case.BatchRunTestCasesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.BatchRunTestCasesRequest): - request = test_case.BatchRunTestCasesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_run_test_cases] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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, - test_case.BatchRunTestCasesResponse, - metadata_type=test_case.BatchRunTestCasesMetadata, - ) - - # Done; return the response. - return response - - def calculate_coverage(self, - request: test_case.CalculateCoverageRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.CalculateCoverageResponse: - r"""Calculates the test coverage for an agent. - - Args: - request (google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest): - The request object. The request message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.CalculateCoverageResponse: - The response message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a test_case.CalculateCoverageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.CalculateCoverageRequest): - request = test_case.CalculateCoverageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.calculate_coverage] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("agent", request.agent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_test_cases(self, - request: test_case.ImportTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. - - Args: - request (google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest): - The request object. The request message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesResponse` - The response message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a test_case.ImportTestCasesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.ImportTestCasesRequest): - request = test_case.ImportTestCasesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_test_cases] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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, - test_case.ImportTestCasesResponse, - metadata_type=test_case.ImportTestCasesMetadata, - ) - - # Done; return the response. - return response - - def export_test_cases(self, - request: test_case.ExportTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. - - Args: - request (google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest): - The request object. The request message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesResponse` - The response message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a test_case.ExportTestCasesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.ExportTestCasesRequest): - request = test_case.ExportTestCasesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_test_cases] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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, - test_case.ExportTestCasesResponse, - metadata_type=test_case.ExportTestCasesMetadata, - ) - - # Done; return the response. - return response - - def list_test_case_results(self, - request: test_case.ListTestCaseResultsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTestCaseResultsPager: - r"""Fetches a list of results for a given test case. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest): - The request object. The request message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. - parent (str): - Required. The test case to list results for. Format: - ``projects//locations//agents// testCases/``. - Specify a ``-`` as a wildcard for TestCase ID to list - results across multiple test cases. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.test_cases.pagers.ListTestCaseResultsPager: - The response message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. - - 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 test_case.ListTestCaseResultsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.ListTestCaseResultsRequest): - request = test_case.ListTestCaseResultsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_test_case_results] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListTestCaseResultsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_test_case_result(self, - request: test_case.GetTestCaseResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.TestCaseResult: - r"""Gets a test case result. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest): - The request object. The request message for - [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. - name (str): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases//results/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.TestCaseResult: - Represents a result from running a - test case in an agent environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a test_case.GetTestCaseResultRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.GetTestCaseResultRequest): - request = test_case.GetTestCaseResultRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_test_case_result] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "TestCasesClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py deleted file mode 100644 index 57840934..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/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.dialogflowcx_v3.types import test_case - - -class ListTestCasesPager: - """A pager for iterating through ``list_test_cases`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``test_cases`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTestCases`` requests and continue to iterate - through the ``test_cases`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` - 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[..., test_case.ListTestCasesResponse], - request: test_case.ListTestCasesRequest, - response: test_case.ListTestCasesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListTestCasesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListTestCasesResponse): - 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 = test_case.ListTestCasesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[test_case.ListTestCasesResponse]: - 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[test_case.TestCase]: - for page in self.pages: - yield from page.test_cases - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTestCasesAsyncPager: - """A pager for iterating through ``list_test_cases`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``test_cases`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTestCases`` requests and continue to iterate - through the ``test_cases`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCasesResponse` - 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[test_case.ListTestCasesResponse]], - request: test_case.ListTestCasesRequest, - response: test_case.ListTestCasesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListTestCasesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListTestCasesResponse): - 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 = test_case.ListTestCasesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[test_case.ListTestCasesResponse]: - 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[test_case.TestCase]: - async def async_generator(): - async for page in self.pages: - for response in page.test_cases: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTestCaseResultsPager: - """A pager for iterating through ``list_test_case_results`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``test_case_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTestCaseResults`` requests and continue to iterate - through the ``test_case_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` - 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[..., test_case.ListTestCaseResultsResponse], - request: test_case.ListTestCaseResultsRequest, - response: test_case.ListTestCaseResultsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse): - 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 = test_case.ListTestCaseResultsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[test_case.ListTestCaseResultsResponse]: - 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[test_case.TestCaseResult]: - for page in self.pages: - yield from page.test_case_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTestCaseResultsAsyncPager: - """A pager for iterating through ``list_test_case_results`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``test_case_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTestCaseResults`` requests and continue to iterate - through the ``test_case_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse` - 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[test_case.ListTestCaseResultsResponse]], - request: test_case.ListTestCaseResultsRequest, - response: test_case.ListTestCaseResultsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListTestCaseResultsResponse): - 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 = test_case.ListTestCaseResultsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[test_case.ListTestCaseResultsResponse]: - 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[test_case.TestCaseResult]: - async def async_generator(): - async for page in self.pages: - for response in page.test_case_results: - 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/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py deleted file mode 100644 index 52d2730d..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/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 TestCasesTransport -from .grpc import TestCasesGrpcTransport -from .grpc_asyncio import TestCasesGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TestCasesTransport]] -_transport_registry['grpc'] = TestCasesGrpcTransport -_transport_registry['grpc_asyncio'] = TestCasesGrpcAsyncIOTransport - -__all__ = ( - 'TestCasesTransport', - 'TestCasesGrpcTransport', - 'TestCasesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py deleted file mode 100644 index 642ea724..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py +++ /dev/null @@ -1,346 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import test_case -from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 # 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-dialogflowcx', - ).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 TestCasesTransport(abc.ABC): - """Abstract transport class for TestCases.""" - - 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_test_cases: gapic_v1.method.wrap_method( - self.list_test_cases, - default_timeout=None, - client_info=client_info, - ), - self.batch_delete_test_cases: gapic_v1.method.wrap_method( - self.batch_delete_test_cases, - default_timeout=None, - client_info=client_info, - ), - self.get_test_case: gapic_v1.method.wrap_method( - self.get_test_case, - default_timeout=None, - client_info=client_info, - ), - self.create_test_case: gapic_v1.method.wrap_method( - self.create_test_case, - default_timeout=None, - client_info=client_info, - ), - self.update_test_case: gapic_v1.method.wrap_method( - self.update_test_case, - default_timeout=None, - client_info=client_info, - ), - self.run_test_case: gapic_v1.method.wrap_method( - self.run_test_case, - default_timeout=None, - client_info=client_info, - ), - self.batch_run_test_cases: gapic_v1.method.wrap_method( - self.batch_run_test_cases, - default_timeout=None, - client_info=client_info, - ), - self.calculate_coverage: gapic_v1.method.wrap_method( - self.calculate_coverage, - default_timeout=None, - client_info=client_info, - ), - self.import_test_cases: gapic_v1.method.wrap_method( - self.import_test_cases, - default_timeout=None, - client_info=client_info, - ), - self.export_test_cases: gapic_v1.method.wrap_method( - self.export_test_cases, - default_timeout=None, - client_info=client_info, - ), - self.list_test_case_results: gapic_v1.method.wrap_method( - self.list_test_case_results, - default_timeout=None, - client_info=client_info, - ), - self.get_test_case_result: gapic_v1.method.wrap_method( - self.get_test_case_result, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_test_cases(self) -> Callable[ - [test_case.ListTestCasesRequest], - Union[ - test_case.ListTestCasesResponse, - Awaitable[test_case.ListTestCasesResponse] - ]]: - raise NotImplementedError() - - @property - def batch_delete_test_cases(self) -> Callable[ - [test_case.BatchDeleteTestCasesRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_test_case(self) -> Callable[ - [test_case.GetTestCaseRequest], - Union[ - test_case.TestCase, - Awaitable[test_case.TestCase] - ]]: - raise NotImplementedError() - - @property - def create_test_case(self) -> Callable[ - [gcdc_test_case.CreateTestCaseRequest], - Union[ - gcdc_test_case.TestCase, - Awaitable[gcdc_test_case.TestCase] - ]]: - raise NotImplementedError() - - @property - def update_test_case(self) -> Callable[ - [gcdc_test_case.UpdateTestCaseRequest], - Union[ - gcdc_test_case.TestCase, - Awaitable[gcdc_test_case.TestCase] - ]]: - raise NotImplementedError() - - @property - def run_test_case(self) -> Callable[ - [test_case.RunTestCaseRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_run_test_cases(self) -> Callable[ - [test_case.BatchRunTestCasesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def calculate_coverage(self) -> Callable[ - [test_case.CalculateCoverageRequest], - Union[ - test_case.CalculateCoverageResponse, - Awaitable[test_case.CalculateCoverageResponse] - ]]: - raise NotImplementedError() - - @property - def import_test_cases(self) -> Callable[ - [test_case.ImportTestCasesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_test_cases(self) -> Callable[ - [test_case.ExportTestCasesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_test_case_results(self) -> Callable[ - [test_case.ListTestCaseResultsRequest], - Union[ - test_case.ListTestCaseResultsResponse, - Awaitable[test_case.ListTestCaseResultsResponse] - ]]: - raise NotImplementedError() - - @property - def get_test_case_result(self) -> Callable[ - [test_case.GetTestCaseResultRequest], - Union[ - test_case.TestCaseResult, - Awaitable[test_case.TestCaseResult] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'TestCasesTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py deleted file mode 100644 index 9b134bfb..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py +++ /dev/null @@ -1,562 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import test_case -from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import TestCasesTransport, DEFAULT_CLIENT_INFO - - -class TestCasesGrpcTransport(TestCasesTransport): - """gRPC backend transport for TestCases. - - Service for managing [Test - Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case - Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. - - 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_test_cases(self) -> Callable[ - [test_case.ListTestCasesRequest], - test_case.ListTestCasesResponse]: - r"""Return a callable for the list test cases method over gRPC. - - Fetches a list of test cases for a given agent. - - Returns: - Callable[[~.ListTestCasesRequest], - ~.ListTestCasesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_test_cases' not in self._stubs: - self._stubs['list_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCases', - request_serializer=test_case.ListTestCasesRequest.serialize, - response_deserializer=test_case.ListTestCasesResponse.deserialize, - ) - return self._stubs['list_test_cases'] - - @property - def batch_delete_test_cases(self) -> Callable[ - [test_case.BatchDeleteTestCasesRequest], - empty_pb2.Empty]: - r"""Return a callable for the batch delete test cases method over gRPC. - - Batch deletes test cases. - - Returns: - Callable[[~.BatchDeleteTestCasesRequest], - ~.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 'batch_delete_test_cases' not in self._stubs: - self._stubs['batch_delete_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/BatchDeleteTestCases', - request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['batch_delete_test_cases'] - - @property - def get_test_case(self) -> Callable[ - [test_case.GetTestCaseRequest], - test_case.TestCase]: - r"""Return a callable for the get test case method over gRPC. - - Gets a test case. - - Returns: - Callable[[~.GetTestCaseRequest], - ~.TestCase]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_test_case' not in self._stubs: - self._stubs['get_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCase', - request_serializer=test_case.GetTestCaseRequest.serialize, - response_deserializer=test_case.TestCase.deserialize, - ) - return self._stubs['get_test_case'] - - @property - def create_test_case(self) -> Callable[ - [gcdc_test_case.CreateTestCaseRequest], - gcdc_test_case.TestCase]: - r"""Return a callable for the create test case method over gRPC. - - Creates a test case for the given agent. - - Returns: - Callable[[~.CreateTestCaseRequest], - ~.TestCase]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_test_case' not in self._stubs: - self._stubs['create_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/CreateTestCase', - request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize, - response_deserializer=gcdc_test_case.TestCase.deserialize, - ) - return self._stubs['create_test_case'] - - @property - def update_test_case(self) -> Callable[ - [gcdc_test_case.UpdateTestCaseRequest], - gcdc_test_case.TestCase]: - r"""Return a callable for the update test case method over gRPC. - - Updates the specified test case. - - Returns: - Callable[[~.UpdateTestCaseRequest], - ~.TestCase]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_test_case' not in self._stubs: - self._stubs['update_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/UpdateTestCase', - request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize, - response_deserializer=gcdc_test_case.TestCase.deserialize, - ) - return self._stubs['update_test_case'] - - @property - def run_test_case(self) -> Callable[ - [test_case.RunTestCaseRequest], - operations_pb2.Operation]: - r"""Return a callable for the run test case method over gRPC. - - Kicks off a test case run. - - Returns: - Callable[[~.RunTestCaseRequest], - ~.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 'run_test_case' not in self._stubs: - self._stubs['run_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/RunTestCase', - request_serializer=test_case.RunTestCaseRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_test_case'] - - @property - def batch_run_test_cases(self) -> Callable[ - [test_case.BatchRunTestCasesRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch run test cases method over gRPC. - - Kicks off a batch run of test cases. - - Returns: - Callable[[~.BatchRunTestCasesRequest], - ~.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_run_test_cases' not in self._stubs: - self._stubs['batch_run_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/BatchRunTestCases', - request_serializer=test_case.BatchRunTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_run_test_cases'] - - @property - def calculate_coverage(self) -> Callable[ - [test_case.CalculateCoverageRequest], - test_case.CalculateCoverageResponse]: - r"""Return a callable for the calculate coverage method over gRPC. - - Calculates the test coverage for an agent. - - Returns: - Callable[[~.CalculateCoverageRequest], - ~.CalculateCoverageResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'calculate_coverage' not in self._stubs: - self._stubs['calculate_coverage'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/CalculateCoverage', - request_serializer=test_case.CalculateCoverageRequest.serialize, - response_deserializer=test_case.CalculateCoverageResponse.deserialize, - ) - return self._stubs['calculate_coverage'] - - @property - def import_test_cases(self) -> Callable[ - [test_case.ImportTestCasesRequest], - operations_pb2.Operation]: - r"""Return a callable for the import test cases method over gRPC. - - Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. - - Returns: - Callable[[~.ImportTestCasesRequest], - ~.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_test_cases' not in self._stubs: - self._stubs['import_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/ImportTestCases', - request_serializer=test_case.ImportTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_test_cases'] - - @property - def export_test_cases(self) -> Callable[ - [test_case.ExportTestCasesRequest], - operations_pb2.Operation]: - r"""Return a callable for the export test cases method over gRPC. - - Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. - - Returns: - Callable[[~.ExportTestCasesRequest], - ~.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_test_cases' not in self._stubs: - self._stubs['export_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/ExportTestCases', - request_serializer=test_case.ExportTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_test_cases'] - - @property - def list_test_case_results(self) -> Callable[ - [test_case.ListTestCaseResultsRequest], - test_case.ListTestCaseResultsResponse]: - r"""Return a callable for the list test case results method over gRPC. - - Fetches a list of results for a given test case. - - Returns: - Callable[[~.ListTestCaseResultsRequest], - ~.ListTestCaseResultsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_test_case_results' not in self._stubs: - self._stubs['list_test_case_results'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCaseResults', - request_serializer=test_case.ListTestCaseResultsRequest.serialize, - response_deserializer=test_case.ListTestCaseResultsResponse.deserialize, - ) - return self._stubs['list_test_case_results'] - - @property - def get_test_case_result(self) -> Callable[ - [test_case.GetTestCaseResultRequest], - test_case.TestCaseResult]: - r"""Return a callable for the get test case result method over gRPC. - - Gets a test case result. - - Returns: - Callable[[~.GetTestCaseResultRequest], - ~.TestCaseResult]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_test_case_result' not in self._stubs: - self._stubs['get_test_case_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCaseResult', - request_serializer=test_case.GetTestCaseResultRequest.serialize, - response_deserializer=test_case.TestCaseResult.deserialize, - ) - return self._stubs['get_test_case_result'] - - -__all__ = ( - 'TestCasesGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py deleted file mode 100644 index 35f5085e..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc_asyncio.py +++ /dev/null @@ -1,566 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import test_case -from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import TestCasesTransport, DEFAULT_CLIENT_INFO -from .grpc import TestCasesGrpcTransport - - -class TestCasesGrpcAsyncIOTransport(TestCasesTransport): - """gRPC AsyncIO backend transport for TestCases. - - Service for managing [Test - Cases][google.cloud.dialogflow.cx.v3.TestCase] and [Test Case - Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. - - 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_test_cases(self) -> Callable[ - [test_case.ListTestCasesRequest], - Awaitable[test_case.ListTestCasesResponse]]: - r"""Return a callable for the list test cases method over gRPC. - - Fetches a list of test cases for a given agent. - - Returns: - Callable[[~.ListTestCasesRequest], - Awaitable[~.ListTestCasesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_test_cases' not in self._stubs: - self._stubs['list_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCases', - request_serializer=test_case.ListTestCasesRequest.serialize, - response_deserializer=test_case.ListTestCasesResponse.deserialize, - ) - return self._stubs['list_test_cases'] - - @property - def batch_delete_test_cases(self) -> Callable[ - [test_case.BatchDeleteTestCasesRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the batch delete test cases method over gRPC. - - Batch deletes test cases. - - Returns: - Callable[[~.BatchDeleteTestCasesRequest], - 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 'batch_delete_test_cases' not in self._stubs: - self._stubs['batch_delete_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/BatchDeleteTestCases', - request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['batch_delete_test_cases'] - - @property - def get_test_case(self) -> Callable[ - [test_case.GetTestCaseRequest], - Awaitable[test_case.TestCase]]: - r"""Return a callable for the get test case method over gRPC. - - Gets a test case. - - Returns: - Callable[[~.GetTestCaseRequest], - Awaitable[~.TestCase]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_test_case' not in self._stubs: - self._stubs['get_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCase', - request_serializer=test_case.GetTestCaseRequest.serialize, - response_deserializer=test_case.TestCase.deserialize, - ) - return self._stubs['get_test_case'] - - @property - def create_test_case(self) -> Callable[ - [gcdc_test_case.CreateTestCaseRequest], - Awaitable[gcdc_test_case.TestCase]]: - r"""Return a callable for the create test case method over gRPC. - - Creates a test case for the given agent. - - Returns: - Callable[[~.CreateTestCaseRequest], - Awaitable[~.TestCase]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_test_case' not in self._stubs: - self._stubs['create_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/CreateTestCase', - request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize, - response_deserializer=gcdc_test_case.TestCase.deserialize, - ) - return self._stubs['create_test_case'] - - @property - def update_test_case(self) -> Callable[ - [gcdc_test_case.UpdateTestCaseRequest], - Awaitable[gcdc_test_case.TestCase]]: - r"""Return a callable for the update test case method over gRPC. - - Updates the specified test case. - - Returns: - Callable[[~.UpdateTestCaseRequest], - Awaitable[~.TestCase]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_test_case' not in self._stubs: - self._stubs['update_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/UpdateTestCase', - request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize, - response_deserializer=gcdc_test_case.TestCase.deserialize, - ) - return self._stubs['update_test_case'] - - @property - def run_test_case(self) -> Callable[ - [test_case.RunTestCaseRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run test case method over gRPC. - - Kicks off a test case run. - - Returns: - Callable[[~.RunTestCaseRequest], - 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 'run_test_case' not in self._stubs: - self._stubs['run_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/RunTestCase', - request_serializer=test_case.RunTestCaseRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_test_case'] - - @property - def batch_run_test_cases(self) -> Callable[ - [test_case.BatchRunTestCasesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch run test cases method over gRPC. - - Kicks off a batch run of test cases. - - Returns: - Callable[[~.BatchRunTestCasesRequest], - 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_run_test_cases' not in self._stubs: - self._stubs['batch_run_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/BatchRunTestCases', - request_serializer=test_case.BatchRunTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_run_test_cases'] - - @property - def calculate_coverage(self) -> Callable[ - [test_case.CalculateCoverageRequest], - Awaitable[test_case.CalculateCoverageResponse]]: - r"""Return a callable for the calculate coverage method over gRPC. - - Calculates the test coverage for an agent. - - Returns: - Callable[[~.CalculateCoverageRequest], - Awaitable[~.CalculateCoverageResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'calculate_coverage' not in self._stubs: - self._stubs['calculate_coverage'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/CalculateCoverage', - request_serializer=test_case.CalculateCoverageRequest.serialize, - response_deserializer=test_case.CalculateCoverageResponse.deserialize, - ) - return self._stubs['calculate_coverage'] - - @property - def import_test_cases(self) -> Callable[ - [test_case.ImportTestCasesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import test cases method over gRPC. - - Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. - - Returns: - Callable[[~.ImportTestCasesRequest], - 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_test_cases' not in self._stubs: - self._stubs['import_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/ImportTestCases', - request_serializer=test_case.ImportTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_test_cases'] - - @property - def export_test_cases(self) -> Callable[ - [test_case.ExportTestCasesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the export test cases method over gRPC. - - Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. - - Returns: - Callable[[~.ExportTestCasesRequest], - 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_test_cases' not in self._stubs: - self._stubs['export_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/ExportTestCases', - request_serializer=test_case.ExportTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_test_cases'] - - @property - def list_test_case_results(self) -> Callable[ - [test_case.ListTestCaseResultsRequest], - Awaitable[test_case.ListTestCaseResultsResponse]]: - r"""Return a callable for the list test case results method over gRPC. - - Fetches a list of results for a given test case. - - Returns: - Callable[[~.ListTestCaseResultsRequest], - Awaitable[~.ListTestCaseResultsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_test_case_results' not in self._stubs: - self._stubs['list_test_case_results'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/ListTestCaseResults', - request_serializer=test_case.ListTestCaseResultsRequest.serialize, - response_deserializer=test_case.ListTestCaseResultsResponse.deserialize, - ) - return self._stubs['list_test_case_results'] - - @property - def get_test_case_result(self) -> Callable[ - [test_case.GetTestCaseResultRequest], - Awaitable[test_case.TestCaseResult]]: - r"""Return a callable for the get test case result method over gRPC. - - Gets a test case result. - - Returns: - Callable[[~.GetTestCaseResultRequest], - Awaitable[~.TestCaseResult]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_test_case_result' not in self._stubs: - self._stubs['get_test_case_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TestCases/GetTestCaseResult', - request_serializer=test_case.GetTestCaseResultRequest.serialize, - response_deserializer=test_case.TestCaseResult.deserialize, - ) - return self._stubs['get_test_case_result'] - - -__all__ = ( - 'TestCasesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py deleted file mode 100644 index 8e43702f..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/__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 TransitionRouteGroupsClient -from .async_client import TransitionRouteGroupsAsyncClient - -__all__ = ( - 'TransitionRouteGroupsClient', - 'TransitionRouteGroupsAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py deleted file mode 100644 index b71fadf0..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/async_client.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.transition_route_groups import pagers -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import transition_route_group -from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport -from .client import TransitionRouteGroupsClient - - -class TransitionRouteGroupsAsyncClient: - """Service for managing - [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - """ - - _client: TransitionRouteGroupsClient - - DEFAULT_ENDPOINT = TransitionRouteGroupsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TransitionRouteGroupsClient.DEFAULT_MTLS_ENDPOINT - - flow_path = staticmethod(TransitionRouteGroupsClient.flow_path) - parse_flow_path = staticmethod(TransitionRouteGroupsClient.parse_flow_path) - intent_path = staticmethod(TransitionRouteGroupsClient.intent_path) - parse_intent_path = staticmethod(TransitionRouteGroupsClient.parse_intent_path) - page_path = staticmethod(TransitionRouteGroupsClient.page_path) - parse_page_path = staticmethod(TransitionRouteGroupsClient.parse_page_path) - transition_route_group_path = staticmethod(TransitionRouteGroupsClient.transition_route_group_path) - parse_transition_route_group_path = staticmethod(TransitionRouteGroupsClient.parse_transition_route_group_path) - webhook_path = staticmethod(TransitionRouteGroupsClient.webhook_path) - parse_webhook_path = staticmethod(TransitionRouteGroupsClient.parse_webhook_path) - common_billing_account_path = staticmethod(TransitionRouteGroupsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TransitionRouteGroupsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TransitionRouteGroupsClient.common_folder_path) - parse_common_folder_path = staticmethod(TransitionRouteGroupsClient.parse_common_folder_path) - common_organization_path = staticmethod(TransitionRouteGroupsClient.common_organization_path) - parse_common_organization_path = staticmethod(TransitionRouteGroupsClient.parse_common_organization_path) - common_project_path = staticmethod(TransitionRouteGroupsClient.common_project_path) - parse_common_project_path = staticmethod(TransitionRouteGroupsClient.parse_common_project_path) - common_location_path = staticmethod(TransitionRouteGroupsClient.common_location_path) - parse_common_location_path = staticmethod(TransitionRouteGroupsClient.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: - TransitionRouteGroupsAsyncClient: The constructed client. - """ - return TransitionRouteGroupsClient.from_service_account_info.__func__(TransitionRouteGroupsAsyncClient, 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: - TransitionRouteGroupsAsyncClient: The constructed client. - """ - return TransitionRouteGroupsClient.from_service_account_file.__func__(TransitionRouteGroupsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> TransitionRouteGroupsTransport: - """Returns the transport used by the client instance. - - Returns: - TransitionRouteGroupsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(TransitionRouteGroupsClient).get_transport_class, type(TransitionRouteGroupsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, TransitionRouteGroupsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the transition route groups 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, ~.TransitionRouteGroupsTransport]): 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 = TransitionRouteGroupsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_transition_route_groups(self, - request: transition_route_group.ListTransitionRouteGroupsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTransitionRouteGroupsAsyncPager: - r"""Returns the list of all transition route groups in - the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest`): - The request object. The request message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. - parent (:class:`str`): - Required. The flow to list all transition route groups - for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.transition_route_groups.pagers.ListTransitionRouteGroupsAsyncPager: - The response message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. - - 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_transition_route_groups, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListTransitionRouteGroupsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_transition_route_group(self, - request: transition_route_group.GetTransitionRouteGroupRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transition_route_group.TransitionRouteGroup: - r"""Retrieves the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetTransitionRouteGroupRequest`): - The request object. The request message for - [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.GetTransitionRouteGroup]. - name (:class:`str`): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = transition_route_group.GetTransitionRouteGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_transition_route_group, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_transition_route_group(self, - request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, - *, - parent: str = None, - transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_transition_route_group.TransitionRouteGroup: - r"""Creates an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - in the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateTransitionRouteGroupRequest`): - The request object. The request message for - [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup]. - parent (:class:`str`): - Required. The flow to create an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - transition_route_group (:class:`google.cloud.dialogflowcx_v3.types.TransitionRouteGroup`): - Required. The transition route group - to create. - - This corresponds to the ``transition_route_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, transition_route_group]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if transition_route_group is not None: - request.transition_route_group = transition_route_group - - # 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_transition_route_group, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_transition_route_group(self, - request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, - *, - transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_transition_route_group.TransitionRouteGroup: - r"""Updates the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateTransitionRouteGroupRequest`): - The request object. The request message for - [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.UpdateTransitionRouteGroup]. - transition_route_group (:class:`google.cloud.dialogflowcx_v3.types.TransitionRouteGroup`): - Required. The transition route group - to update. - - This corresponds to the ``transition_route_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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.dialogflowcx_v3.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([transition_route_group, 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 = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if transition_route_group is not None: - request.transition_route_group = transition_route_group - if update_mask is not None: - 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_transition_route_group, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("transition_route_group.name", request.transition_route_group.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_transition_route_group(self, - request: transition_route_group.DeleteTransitionRouteGroupRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteTransitionRouteGroupRequest`): - The request object. The request message for - [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.DeleteTransitionRouteGroup]. - name (:class:`str`): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - to delete. Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = transition_route_group.DeleteTransitionRouteGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_transition_route_group, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "TransitionRouteGroupsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py deleted file mode 100644 index 0eef6fe4..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/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.dialogflowcx_v3.services.transition_route_groups import pagers -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import transition_route_group -from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TransitionRouteGroupsGrpcTransport -from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport - - -class TransitionRouteGroupsClientMeta(type): - """Metaclass for the TransitionRouteGroups 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[TransitionRouteGroupsTransport]] - _transport_registry["grpc"] = TransitionRouteGroupsGrpcTransport - _transport_registry["grpc_asyncio"] = TransitionRouteGroupsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[TransitionRouteGroupsTransport]: - """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 TransitionRouteGroupsClient(metaclass=TransitionRouteGroupsClientMeta): - """Service for managing - [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - """ - - @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: - TransitionRouteGroupsClient: 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: - TransitionRouteGroupsClient: 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) -> TransitionRouteGroupsTransport: - """Returns the transport used by the client instance. - - Returns: - TransitionRouteGroupsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: - """Returns a fully-qualified page string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - - @staticmethod - def parse_page_path(path: str) -> Dict[str,str]: - """Parses a page path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: - """Returns a fully-qualified transition_route_group string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - - @staticmethod - def parse_transition_route_group_path(path: str) -> Dict[str,str]: - """Parses a transition_route_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, TransitionRouteGroupsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the transition route groups 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, TransitionRouteGroupsTransport]): 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, TransitionRouteGroupsTransport): - # transport is a TransitionRouteGroupsTransport 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_transition_route_groups(self, - request: transition_route_group.ListTransitionRouteGroupsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTransitionRouteGroupsPager: - r"""Returns the list of all transition route groups in - the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest): - The request object. The request message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. - parent (str): - Required. The flow to list all transition route groups - for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.transition_route_groups.pagers.ListTransitionRouteGroupsPager: - The response message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. - - 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 transition_route_group.ListTransitionRouteGroupsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, transition_route_group.ListTransitionRouteGroupsRequest): - request = transition_route_group.ListTransitionRouteGroupsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_transition_route_groups] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListTransitionRouteGroupsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_transition_route_group(self, - request: transition_route_group.GetTransitionRouteGroupRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transition_route_group.TransitionRouteGroup: - r"""Retrieves the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetTransitionRouteGroupRequest): - The request object. The request message for - [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.GetTransitionRouteGroup]. - name (str): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 transition_route_group.GetTransitionRouteGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, transition_route_group.GetTransitionRouteGroupRequest): - request = transition_route_group.GetTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_transition_route_group] - - # Certain fields should be provided 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_transition_route_group(self, - request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, - *, - parent: str = None, - transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_transition_route_group.TransitionRouteGroup: - r"""Creates an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - in the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateTransitionRouteGroupRequest): - The request object. The request message for - [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup]. - parent (str): - Required. The flow to create an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - transition_route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): - Required. The transition route group - to create. - - This corresponds to the ``transition_route_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, transition_route_group]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_transition_route_group.CreateTransitionRouteGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_transition_route_group.CreateTransitionRouteGroupRequest): - request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if transition_route_group is not None: - request.transition_route_group = transition_route_group - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_transition_route_group] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_transition_route_group(self, - request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, - *, - transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_transition_route_group.TransitionRouteGroup: - r"""Updates the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateTransitionRouteGroupRequest): - The request object. The request message for - [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.UpdateTransitionRouteGroup]. - transition_route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): - Required. The transition route group - to update. - - This corresponds to the ``transition_route_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.dialogflowcx_v3.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([transition_route_group, 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 gcdc_transition_route_group.UpdateTransitionRouteGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): - request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if transition_route_group is not None: - request.transition_route_group = transition_route_group - if update_mask is not None: - 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_transition_route_group] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("transition_route_group.name", request.transition_route_group.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_transition_route_group(self, - request: transition_route_group.DeleteTransitionRouteGroupRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Args: - request (google.cloud.dialogflowcx_v3.types.DeleteTransitionRouteGroupRequest): - The request object. The request message for - [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.DeleteTransitionRouteGroup]. - name (str): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - to delete. Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 transition_route_group.DeleteTransitionRouteGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, transition_route_group.DeleteTransitionRouteGroupRequest): - request = transition_route_group.DeleteTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_transition_route_group] - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "TransitionRouteGroupsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py deleted file mode 100644 index e14f7b04..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/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.dialogflowcx_v3.types import transition_route_group - - -class ListTransitionRouteGroupsPager: - """A pager for iterating through ``list_transition_route_groups`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``transition_route_groups`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTransitionRouteGroups`` requests and continue to iterate - through the ``transition_route_groups`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` - 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[..., transition_route_group.ListTransitionRouteGroupsResponse], - request: transition_route_group.ListTransitionRouteGroupsRequest, - response: transition_route_group.ListTransitionRouteGroupsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse): - 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[transition_route_group.ListTransitionRouteGroupsResponse]: - 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[transition_route_group.TransitionRouteGroup]: - for page in self.pages: - yield from page.transition_route_groups - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTransitionRouteGroupsAsyncPager: - """A pager for iterating through ``list_transition_route_groups`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``transition_route_groups`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTransitionRouteGroups`` requests and continue to iterate - through the ``transition_route_groups`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse` - 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[transition_route_group.ListTransitionRouteGroupsResponse]], - request: transition_route_group.ListTransitionRouteGroupsRequest, - response: transition_route_group.ListTransitionRouteGroupsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListTransitionRouteGroupsResponse): - 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[transition_route_group.ListTransitionRouteGroupsResponse]: - 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[transition_route_group.TransitionRouteGroup]: - async def async_generator(): - async for page in self.pages: - for response in page.transition_route_groups: - 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/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py deleted file mode 100644 index 50e891f2..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/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 TransitionRouteGroupsTransport -from .grpc import TransitionRouteGroupsGrpcTransport -from .grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TransitionRouteGroupsTransport]] -_transport_registry['grpc'] = TransitionRouteGroupsGrpcTransport -_transport_registry['grpc_asyncio'] = TransitionRouteGroupsGrpcAsyncIOTransport - -__all__ = ( - 'TransitionRouteGroupsTransport', - 'TransitionRouteGroupsGrpcTransport', - 'TransitionRouteGroupsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/base.py deleted file mode 100644 index 92e31a6b..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/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.dialogflowcx_v3.types import transition_route_group -from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflowcx', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class TransitionRouteGroupsTransport(abc.ABC): - """Abstract transport class for TransitionRouteGroups.""" - - 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_transition_route_groups: gapic_v1.method.wrap_method( - self.list_transition_route_groups, - default_timeout=None, - client_info=client_info, - ), - self.get_transition_route_group: gapic_v1.method.wrap_method( - self.get_transition_route_group, - default_timeout=None, - client_info=client_info, - ), - self.create_transition_route_group: gapic_v1.method.wrap_method( - self.create_transition_route_group, - default_timeout=None, - client_info=client_info, - ), - self.update_transition_route_group: gapic_v1.method.wrap_method( - self.update_transition_route_group, - default_timeout=None, - client_info=client_info, - ), - self.delete_transition_route_group: gapic_v1.method.wrap_method( - self.delete_transition_route_group, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_transition_route_groups(self) -> Callable[ - [transition_route_group.ListTransitionRouteGroupsRequest], - Union[ - transition_route_group.ListTransitionRouteGroupsResponse, - Awaitable[transition_route_group.ListTransitionRouteGroupsResponse] - ]]: - raise NotImplementedError() - - @property - def get_transition_route_group(self) -> Callable[ - [transition_route_group.GetTransitionRouteGroupRequest], - Union[ - transition_route_group.TransitionRouteGroup, - Awaitable[transition_route_group.TransitionRouteGroup] - ]]: - raise NotImplementedError() - - @property - def create_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], - Union[ - gcdc_transition_route_group.TransitionRouteGroup, - Awaitable[gcdc_transition_route_group.TransitionRouteGroup] - ]]: - raise NotImplementedError() - - @property - def update_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], - Union[ - gcdc_transition_route_group.TransitionRouteGroup, - Awaitable[gcdc_transition_route_group.TransitionRouteGroup] - ]]: - raise NotImplementedError() - - @property - def delete_transition_route_group(self) -> Callable[ - [transition_route_group.DeleteTransitionRouteGroupRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'TransitionRouteGroupsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py deleted file mode 100644 index 4987008c..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py +++ /dev/null @@ -1,361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflowcx_v3.types import transition_route_group -from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group -from google.protobuf import empty_pb2 # type: ignore -from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO - - -class TransitionRouteGroupsGrpcTransport(TransitionRouteGroupsTransport): - """gRPC backend transport for TransitionRouteGroups. - - Service for managing - [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - 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_transition_route_groups(self) -> Callable[ - [transition_route_group.ListTransitionRouteGroupsRequest], - transition_route_group.ListTransitionRouteGroupsResponse]: - r"""Return a callable for the list transition route groups method over gRPC. - - Returns the list of all transition route groups in - the specified flow. - - Returns: - Callable[[~.ListTransitionRouteGroupsRequest], - ~.ListTransitionRouteGroupsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_transition_route_groups' not in self._stubs: - self._stubs['list_transition_route_groups'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/ListTransitionRouteGroups', - request_serializer=transition_route_group.ListTransitionRouteGroupsRequest.serialize, - response_deserializer=transition_route_group.ListTransitionRouteGroupsResponse.deserialize, - ) - return self._stubs['list_transition_route_groups'] - - @property - def get_transition_route_group(self) -> Callable[ - [transition_route_group.GetTransitionRouteGroupRequest], - transition_route_group.TransitionRouteGroup]: - r"""Return a callable for the get transition route group method over gRPC. - - Retrieves the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Returns: - Callable[[~.GetTransitionRouteGroupRequest], - ~.TransitionRouteGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_transition_route_group' not in self._stubs: - self._stubs['get_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/GetTransitionRouteGroup', - request_serializer=transition_route_group.GetTransitionRouteGroupRequest.serialize, - response_deserializer=transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['get_transition_route_group'] - - @property - def create_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], - gcdc_transition_route_group.TransitionRouteGroup]: - r"""Return a callable for the create transition route group method over gRPC. - - Creates an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - in the specified flow. - - Returns: - Callable[[~.CreateTransitionRouteGroupRequest], - ~.TransitionRouteGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: - self._stubs['create_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/CreateTransitionRouteGroup', - request_serializer=gcdc_transition_route_group.CreateTransitionRouteGroupRequest.serialize, - response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['create_transition_route_group'] - - @property - def update_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], - gcdc_transition_route_group.TransitionRouteGroup]: - r"""Return a callable for the update transition route group method over gRPC. - - Updates the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Returns: - Callable[[~.UpdateTransitionRouteGroupRequest], - ~.TransitionRouteGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: - self._stubs['update_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/UpdateTransitionRouteGroup', - request_serializer=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.serialize, - response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['update_transition_route_group'] - - @property - def delete_transition_route_group(self) -> Callable[ - [transition_route_group.DeleteTransitionRouteGroupRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete transition route group method over gRPC. - - Deletes the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Returns: - Callable[[~.DeleteTransitionRouteGroupRequest], - ~.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_transition_route_group' not in self._stubs: - self._stubs['delete_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/DeleteTransitionRouteGroup', - request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_transition_route_group'] - - -__all__ = ( - 'TransitionRouteGroupsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py deleted file mode 100644 index ad065da6..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc_asyncio.py +++ /dev/null @@ -1,365 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import transition_route_group -from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group -from google.protobuf import empty_pb2 # type: ignore -from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO -from .grpc import TransitionRouteGroupsGrpcTransport - - -class TransitionRouteGroupsGrpcAsyncIOTransport(TransitionRouteGroupsTransport): - """gRPC AsyncIO backend transport for TransitionRouteGroups. - - Service for managing - [TransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - 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_transition_route_groups(self) -> Callable[ - [transition_route_group.ListTransitionRouteGroupsRequest], - Awaitable[transition_route_group.ListTransitionRouteGroupsResponse]]: - r"""Return a callable for the list transition route groups method over gRPC. - - Returns the list of all transition route groups in - the specified flow. - - Returns: - Callable[[~.ListTransitionRouteGroupsRequest], - Awaitable[~.ListTransitionRouteGroupsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_transition_route_groups' not in self._stubs: - self._stubs['list_transition_route_groups'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/ListTransitionRouteGroups', - request_serializer=transition_route_group.ListTransitionRouteGroupsRequest.serialize, - response_deserializer=transition_route_group.ListTransitionRouteGroupsResponse.deserialize, - ) - return self._stubs['list_transition_route_groups'] - - @property - def get_transition_route_group(self) -> Callable[ - [transition_route_group.GetTransitionRouteGroupRequest], - Awaitable[transition_route_group.TransitionRouteGroup]]: - r"""Return a callable for the get transition route group method over gRPC. - - Retrieves the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Returns: - Callable[[~.GetTransitionRouteGroupRequest], - Awaitable[~.TransitionRouteGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_transition_route_group' not in self._stubs: - self._stubs['get_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/GetTransitionRouteGroup', - request_serializer=transition_route_group.GetTransitionRouteGroupRequest.serialize, - response_deserializer=transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['get_transition_route_group'] - - @property - def create_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], - Awaitable[gcdc_transition_route_group.TransitionRouteGroup]]: - r"""Return a callable for the create transition route group method over gRPC. - - Creates an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - in the specified flow. - - Returns: - Callable[[~.CreateTransitionRouteGroupRequest], - Awaitable[~.TransitionRouteGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: - self._stubs['create_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/CreateTransitionRouteGroup', - request_serializer=gcdc_transition_route_group.CreateTransitionRouteGroupRequest.serialize, - response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['create_transition_route_group'] - - @property - def update_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], - Awaitable[gcdc_transition_route_group.TransitionRouteGroup]]: - r"""Return a callable for the update transition route group method over gRPC. - - Updates the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Returns: - Callable[[~.UpdateTransitionRouteGroupRequest], - Awaitable[~.TransitionRouteGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: - self._stubs['update_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/UpdateTransitionRouteGroup', - request_serializer=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.serialize, - response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['update_transition_route_group'] - - @property - def delete_transition_route_group(self) -> Callable[ - [transition_route_group.DeleteTransitionRouteGroupRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete transition route group method over gRPC. - - Deletes the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - - Returns: - Callable[[~.DeleteTransitionRouteGroupRequest], - 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_transition_route_group' not in self._stubs: - self._stubs['delete_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/DeleteTransitionRouteGroup', - request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_transition_route_group'] - - -__all__ = ( - 'TransitionRouteGroupsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__init__.py deleted file mode 100644 index 630246bd..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/__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 VersionsClient -from .async_client import VersionsAsyncClient - -__all__ = ( - 'VersionsClient', - 'VersionsAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py deleted file mode 100644 index f89676b3..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/async_client.py +++ /dev/null @@ -1,687 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.versions import pagers -from google.cloud.dialogflowcx_v3.types import flow -from google.cloud.dialogflowcx_v3.types import version -from google.cloud.dialogflowcx_v3.types import version as gcdc_version -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport -from .client import VersionsClient - - -class VersionsAsyncClient: - """Service for managing - [Versions][google.cloud.dialogflow.cx.v3.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 in the specified - [Flow][google.cloud.dialogflow.cx.v3.Flow]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListVersionsRequest`): - The request object. The request message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. - parent (:class:`str`): - Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] - to list all versions for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.versions.pagers.ListVersionsAsyncPager: - The response message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3.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 - [Version][google.cloud.dialogflow.cx.v3.Version]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetVersionRequest`): - The request object. The request message for - [Versions.GetVersion][google.cloud.dialogflow.cx.v3.Versions.GetVersion]. - name (:class:`str`): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3.Version]. - Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Version: - Represents a version of a flow. - """ - # Create or coerce a protobuf request object. - # Sanity check: 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: gcdc_version.CreateVersionRequest = None, - *, - parent: str = None, - version: gcdc_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in - the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateVersionRequest`): - The request object. The request message for - [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. - parent (:class:`str`): - Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] - to create an - [Version][google.cloud.dialogflow.cx.v3.Version] for. - Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - version (:class:`google.cloud.dialogflowcx_v3.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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.Version` - Represents a version of a flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = gcdc_version.CreateVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if version is not None: - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcdc_version.Version, - metadata_type=gcdc_version.CreateVersionOperationMetadata, - ) - - # Done; return the response. - return response - - async def update_version(self, - request: gcdc_version.UpdateVersionRequest = None, - *, - version: gcdc_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]] = (), - ) -> gcdc_version.Version: - r"""Updates the specified - [Version][google.cloud.dialogflow.cx.v3.Version]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateVersionRequest`): - The request object. The request message for - [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3.Versions.UpdateVersion]. - version (:class:`google.cloud.dialogflowcx_v3.types.Version`): - Required. The version to update. - 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. - Currently only ``description`` and ``display_name`` can - 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.dialogflowcx_v3.types.Version: - Represents a version of a flow. - """ - # Create or coerce a protobuf request object. - # Sanity 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 = gcdc_version.UpdateVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if version is not None: - request.version = version - if update_mask is not None: - 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"""Deletes the specified - [Version][google.cloud.dialogflow.cx.v3.Version]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteVersionRequest`): - The request object. The request message for - [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3.Versions.DeleteVersion]. - name (:class:`str`): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3.Version] to - delete. Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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, - ) - - async def load_version(self, - request: version.LoadVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Loads resources in the specified version to the draft - flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.LoadVersionRequest`): - The request object. The request message for - [Versions.LoadVersion][google.cloud.dialogflow.cx.v3.Versions.LoadVersion]. - name (:class:`str`): - Required. The - [Version][google.cloud.dialogflow.cx.v3.Version] to be - loaded to draft flow. Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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 = version.LoadVersionRequest(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.load_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, - ) - - # 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VersionsAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py deleted file mode 100644 index 37c1918b..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/client.py +++ /dev/null @@ -1,874 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.versions import pagers -from google.cloud.dialogflowcx_v3.types import flow -from google.cloud.dialogflowcx_v3.types import version -from google.cloud.dialogflowcx_v3.types import version as gcdc_version -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import VersionsGrpcTransport -from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport - - -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.cx.v3.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,location: str,agent: str,flow: str,version: str,) -> str: - """Returns a fully-qualified version string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - - @staticmethod - def parse_version_path(path: str) -> Dict[str,str]: - """Parses a version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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 in the specified - [Flow][google.cloud.dialogflow.cx.v3.Flow]. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListVersionsRequest): - The request object. The request message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. - parent (str): - Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] - to list all versions for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.versions.pagers.ListVersionsPager: - The response message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3.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 - [Version][google.cloud.dialogflow.cx.v3.Version]. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetVersionRequest): - The request object. The request message for - [Versions.GetVersion][google.cloud.dialogflow.cx.v3.Versions.GetVersion]. - name (str): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3.Version]. - Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Version: - Represents a version of a flow. - """ - # Create or coerce a protobuf request object. - # Sanity check: 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: gcdc_version.CreateVersionRequest = None, - *, - parent: str = None, - version: gcdc_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in - the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateVersionRequest): - The request object. The request message for - [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. - parent (str): - Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] - to create an - [Version][google.cloud.dialogflow.cx.v3.Version] for. - Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - version (google.cloud.dialogflowcx_v3.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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3.types.Version` - Represents a version of a flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 gcdc_version.CreateVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_version.CreateVersionRequest): - request = gcdc_version.CreateVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if version is not None: - 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcdc_version.Version, - metadata_type=gcdc_version.CreateVersionOperationMetadata, - ) - - # Done; return the response. - return response - - def update_version(self, - request: gcdc_version.UpdateVersionRequest = None, - *, - version: gcdc_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]] = (), - ) -> gcdc_version.Version: - r"""Updates the specified - [Version][google.cloud.dialogflow.cx.v3.Version]. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateVersionRequest): - The request object. The request message for - [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3.Versions.UpdateVersion]. - version (google.cloud.dialogflowcx_v3.types.Version): - Required. The version to update. - 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. - Currently only ``description`` and ``display_name`` can - 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.dialogflowcx_v3.types.Version: - Represents a version of a flow. - """ - # Create or coerce a protobuf request object. - # Sanity 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 gcdc_version.UpdateVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_version.UpdateVersionRequest): - request = gcdc_version.UpdateVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if version is not None: - request.version = version - if update_mask is not None: - 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"""Deletes the specified - [Version][google.cloud.dialogflow.cx.v3.Version]. - - Args: - request (google.cloud.dialogflowcx_v3.types.DeleteVersionRequest): - The request object. The request message for - [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3.Versions.DeleteVersion]. - name (str): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3.Version] to - delete. Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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, - ) - - def load_version(self, - request: version.LoadVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Loads resources in the specified version to the draft - flow. - - Args: - request (google.cloud.dialogflowcx_v3.types.LoadVersionRequest): - The request object. The request message for - [Versions.LoadVersion][google.cloud.dialogflow.cx.v3.Versions.LoadVersion]. - name (str): - Required. The - [Version][google.cloud.dialogflow.cx.v3.Version] to be - loaded to draft flow. Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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 version.LoadVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, version.LoadVersionRequest): - request = version.LoadVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.load_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, - ) - - # 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VersionsClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/pagers.py deleted file mode 100644 index 1c20a2e4..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/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.dialogflowcx_v3.types import version - - -class ListVersionsPager: - """A pager for iterating through ``list_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListVersionsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.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.dialogflowcx_v3.types.ListVersionsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.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/v3/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py deleted file mode 100644 index dfb70ce9..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/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 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/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.py deleted file mode 100644 index b92ce225..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/base.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. -# -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.dialogflowcx_v3.types import version -from google.cloud.dialogflowcx_v3.types import version as gcdc_version -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-dialogflowcx', - ).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, - ), - self.load_version: gapic_v1.method.wrap_method( - self.load_version, - 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_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[ - [gcdc_version.CreateVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_version(self) -> Callable[ - [gcdc_version.UpdateVersionRequest], - Union[ - gcdc_version.Version, - Awaitable[gcdc_version.Version] - ]]: - raise NotImplementedError() - - @property - def delete_version(self) -> Callable[ - [version.DeleteVersionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def load_version(self) -> Callable[ - [version.LoadVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'VersionsTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py deleted file mode 100644 index 62e44d60..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.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. -# -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.dialogflowcx_v3.types import version -from google.cloud.dialogflowcx_v3.types import version as gcdc_version -from google.longrunning import operations_pb2 # type: ignore -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.cx.v3.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] = {} - 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_versions(self) -> Callable[ - [version.ListVersionsRequest], - version.ListVersionsResponse]: - r"""Return a callable for the list versions method over gRPC. - - Returns the list of all versions in the specified - [Flow][google.cloud.dialogflow.cx.v3.Flow]. - - 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.cx.v3.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 - [Version][google.cloud.dialogflow.cx.v3.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.cx.v3.Versions/GetVersion', - request_serializer=version.GetVersionRequest.serialize, - response_deserializer=version.Version.deserialize, - ) - return self._stubs['get_version'] - - @property - def create_version(self) -> Callable[ - [gcdc_version.CreateVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create version method over gRPC. - - Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in - the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. - - Returns: - Callable[[~.CreateVersionRequest], - ~.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_version' not in self._stubs: - self._stubs['create_version'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Versions/CreateVersion', - request_serializer=gcdc_version.CreateVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_version'] - - @property - def update_version(self) -> Callable[ - [gcdc_version.UpdateVersionRequest], - gcdc_version.Version]: - r"""Return a callable for the update version method over gRPC. - - Updates the specified - [Version][google.cloud.dialogflow.cx.v3.Version]. - - 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.cx.v3.Versions/UpdateVersion', - request_serializer=gcdc_version.UpdateVersionRequest.serialize, - response_deserializer=gcdc_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. - - Deletes the specified - [Version][google.cloud.dialogflow.cx.v3.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.cx.v3.Versions/DeleteVersion', - request_serializer=version.DeleteVersionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_version'] - - @property - def load_version(self) -> Callable[ - [version.LoadVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the load version method over gRPC. - - Loads resources in the specified version to the draft - flow. - - Returns: - Callable[[~.LoadVersionRequest], - ~.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 'load_version' not in self._stubs: - self._stubs['load_version'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Versions/LoadVersion', - request_serializer=version.LoadVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['load_version'] - - -__all__ = ( - 'VersionsGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py deleted file mode 100644 index 5a53e233..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py +++ /dev/null @@ -1,410 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import version -from google.cloud.dialogflowcx_v3.types import version as gcdc_version -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import VersionsTransport, DEFAULT_CLIENT_INFO -from .grpc import VersionsGrpcTransport - - -class VersionsGrpcAsyncIOTransport(VersionsTransport): - """gRPC AsyncIO backend transport for Versions. - - Service for managing - [Versions][google.cloud.dialogflow.cx.v3.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] = {} - 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_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 in the specified - [Flow][google.cloud.dialogflow.cx.v3.Flow]. - - 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.cx.v3.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 - [Version][google.cloud.dialogflow.cx.v3.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.cx.v3.Versions/GetVersion', - request_serializer=version.GetVersionRequest.serialize, - response_deserializer=version.Version.deserialize, - ) - return self._stubs['get_version'] - - @property - def create_version(self) -> Callable[ - [gcdc_version.CreateVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create version method over gRPC. - - Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in - the specified [Flow][google.cloud.dialogflow.cx.v3.Flow]. - - Returns: - Callable[[~.CreateVersionRequest], - 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_version' not in self._stubs: - self._stubs['create_version'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Versions/CreateVersion', - request_serializer=gcdc_version.CreateVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_version'] - - @property - def update_version(self) -> Callable[ - [gcdc_version.UpdateVersionRequest], - Awaitable[gcdc_version.Version]]: - r"""Return a callable for the update version method over gRPC. - - Updates the specified - [Version][google.cloud.dialogflow.cx.v3.Version]. - - 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.cx.v3.Versions/UpdateVersion', - request_serializer=gcdc_version.UpdateVersionRequest.serialize, - response_deserializer=gcdc_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. - - Deletes the specified - [Version][google.cloud.dialogflow.cx.v3.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.cx.v3.Versions/DeleteVersion', - request_serializer=version.DeleteVersionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_version'] - - @property - def load_version(self) -> Callable[ - [version.LoadVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the load version method over gRPC. - - Loads resources in the specified version to the draft - flow. - - Returns: - Callable[[~.LoadVersionRequest], - 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 'load_version' not in self._stubs: - self._stubs['load_version'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Versions/LoadVersion', - request_serializer=version.LoadVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['load_version'] - - -__all__ = ( - 'VersionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py deleted file mode 100644 index 8ace8262..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/__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 WebhooksClient -from .async_client import WebhooksAsyncClient - -__all__ = ( - 'WebhooksClient', - 'WebhooksAsyncClient', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py deleted file mode 100644 index d0bbe6dd..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py +++ /dev/null @@ -1,581 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.webhooks import pagers -from google.cloud.dialogflowcx_v3.types import webhook -from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport -from .client import WebhooksClient - - -class WebhooksAsyncClient: - """Service for managing - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. - """ - - _client: WebhooksClient - - DEFAULT_ENDPOINT = WebhooksClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WebhooksClient.DEFAULT_MTLS_ENDPOINT - - service_path = staticmethod(WebhooksClient.service_path) - parse_service_path = staticmethod(WebhooksClient.parse_service_path) - webhook_path = staticmethod(WebhooksClient.webhook_path) - parse_webhook_path = staticmethod(WebhooksClient.parse_webhook_path) - common_billing_account_path = staticmethod(WebhooksClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WebhooksClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WebhooksClient.common_folder_path) - parse_common_folder_path = staticmethod(WebhooksClient.parse_common_folder_path) - common_organization_path = staticmethod(WebhooksClient.common_organization_path) - parse_common_organization_path = staticmethod(WebhooksClient.parse_common_organization_path) - common_project_path = staticmethod(WebhooksClient.common_project_path) - parse_common_project_path = staticmethod(WebhooksClient.parse_common_project_path) - common_location_path = staticmethod(WebhooksClient.common_location_path) - parse_common_location_path = staticmethod(WebhooksClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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: - WebhooksAsyncClient: The constructed client. - """ - return WebhooksClient.from_service_account_info.__func__(WebhooksAsyncClient, 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: - WebhooksAsyncClient: The constructed client. - """ - return WebhooksClient.from_service_account_file.__func__(WebhooksAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> WebhooksTransport: - """Returns the transport used by the client instance. - - Returns: - WebhooksTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(WebhooksClient).get_transport_class, type(WebhooksClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, WebhooksTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the webhooks 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, ~.WebhooksTransport]): 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 = WebhooksClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_webhooks(self, - request: webhook.ListWebhooksRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWebhooksAsyncPager: - r"""Returns the list of all webhooks in the specified - agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.ListWebhooksRequest`): - The request object. The request message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. - parent (:class:`str`): - Required. The agent to list all webhooks for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.webhooks.pagers.ListWebhooksAsyncPager: - The response message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. - - 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 = webhook.ListWebhooksRequest(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_webhooks, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListWebhooksAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_webhook(self, - request: webhook.GetWebhookRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> webhook.Webhook: - r"""Retrieves the specified webhook. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.GetWebhookRequest`): - The request object. The request message for - [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3.Webhooks.GetWebhook]. - name (:class:`str`): - Required. The name of the webhook. Format: - ``projects//locations//agents//webhooks/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = webhook.GetWebhookRequest(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_webhook, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_webhook(self, - request: gcdc_webhook.CreateWebhookRequest = None, - *, - parent: str = None, - webhook: gcdc_webhook.Webhook = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_webhook.Webhook: - r"""Creates a webhook in the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.CreateWebhookRequest`): - The request object. The request message for - [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook]. - parent (:class:`str`): - Required. The agent to create a webhook for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - webhook (:class:`google.cloud.dialogflowcx_v3.types.Webhook`): - Required. The webhook to create. - This corresponds to the ``webhook`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, webhook]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_webhook.CreateWebhookRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if webhook is not None: - request.webhook = webhook - - # 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_webhook, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_webhook(self, - request: gcdc_webhook.UpdateWebhookRequest = None, - *, - webhook: gcdc_webhook.Webhook = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_webhook.Webhook: - r"""Updates the specified webhook. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.UpdateWebhookRequest`): - The request object. The request message for - [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook]. - webhook (:class:`google.cloud.dialogflowcx_v3.types.Webhook`): - Required. The webhook to update. - This corresponds to the ``webhook`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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.dialogflowcx_v3.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([webhook, 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 = gcdc_webhook.UpdateWebhookRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if webhook is not None: - request.webhook = webhook - if update_mask is not None: - 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_webhook, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("webhook.name", request.webhook.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_webhook(self, - request: webhook.DeleteWebhookRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified webhook. - - Args: - request (:class:`google.cloud.dialogflowcx_v3.types.DeleteWebhookRequest`): - The request object. The request message for - [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3.Webhooks.DeleteWebhook]. - name (:class:`str`): - Required. The name of the webhook to delete. Format: - ``projects//locations//agents//webhooks/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = webhook.DeleteWebhookRequest(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_webhook, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "WebhooksAsyncClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py deleted file mode 100644 index 564ed5ab..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/client.py +++ /dev/null @@ -1,777 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3.services.webhooks import pagers -from google.cloud.dialogflowcx_v3.types import webhook -from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WebhooksGrpcTransport -from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport - - -class WebhooksClientMeta(type): - """Metaclass for the Webhooks 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[WebhooksTransport]] - _transport_registry["grpc"] = WebhooksGrpcTransport - _transport_registry["grpc_asyncio"] = WebhooksGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[WebhooksTransport]: - """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 WebhooksClient(metaclass=WebhooksClientMeta): - """Service for managing - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. - """ - - @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: - WebhooksClient: 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: - WebhooksClient: 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) -> WebhooksTransport: - """Returns the transport used by the client instance. - - Returns: - WebhooksTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def service_path(project: str,location: str,namespace: str,service: str,) -> str: - """Returns a fully-qualified service string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - - @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: - """Parses a service path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, WebhooksTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the webhooks 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, WebhooksTransport]): 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, WebhooksTransport): - # transport is a WebhooksTransport 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_webhooks(self, - request: webhook.ListWebhooksRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWebhooksPager: - r"""Returns the list of all webhooks in the specified - agent. - - Args: - request (google.cloud.dialogflowcx_v3.types.ListWebhooksRequest): - The request object. The request message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. - parent (str): - Required. The agent to list all webhooks for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.services.webhooks.pagers.ListWebhooksPager: - The response message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. - - 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 webhook.ListWebhooksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, webhook.ListWebhooksRequest): - request = webhook.ListWebhooksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_webhooks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListWebhooksPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_webhook(self, - request: webhook.GetWebhookRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> webhook.Webhook: - r"""Retrieves the specified webhook. - - Args: - request (google.cloud.dialogflowcx_v3.types.GetWebhookRequest): - The request object. The request message for - [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3.Webhooks.GetWebhook]. - name (str): - Required. The name of the webhook. Format: - ``projects//locations//agents//webhooks/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 webhook.GetWebhookRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, webhook.GetWebhookRequest): - request = webhook.GetWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_webhook] - - # Certain fields should be provided 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_webhook(self, - request: gcdc_webhook.CreateWebhookRequest = None, - *, - parent: str = None, - webhook: gcdc_webhook.Webhook = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_webhook.Webhook: - r"""Creates a webhook in the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3.types.CreateWebhookRequest): - The request object. The request message for - [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook]. - parent (str): - Required. The agent to create a webhook for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - webhook (google.cloud.dialogflowcx_v3.types.Webhook): - Required. The webhook to create. - This corresponds to the ``webhook`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, webhook]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_webhook.CreateWebhookRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_webhook.CreateWebhookRequest): - request = gcdc_webhook.CreateWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if webhook is not None: - request.webhook = webhook - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_webhook] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_webhook(self, - request: gcdc_webhook.UpdateWebhookRequest = None, - *, - webhook: gcdc_webhook.Webhook = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_webhook.Webhook: - r"""Updates the specified webhook. - - Args: - request (google.cloud.dialogflowcx_v3.types.UpdateWebhookRequest): - The request object. The request message for - [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook]. - webhook (google.cloud.dialogflowcx_v3.types.Webhook): - Required. The webhook to update. - This corresponds to the ``webhook`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.dialogflowcx_v3.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([webhook, 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 gcdc_webhook.UpdateWebhookRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_webhook.UpdateWebhookRequest): - request = gcdc_webhook.UpdateWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if webhook is not None: - request.webhook = webhook - if update_mask is not None: - 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_webhook] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("webhook.name", request.webhook.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_webhook(self, - request: webhook.DeleteWebhookRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified webhook. - - Args: - request (google.cloud.dialogflowcx_v3.types.DeleteWebhookRequest): - The request object. The request message for - [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3.Webhooks.DeleteWebhook]. - name (str): - Required. The name of the webhook to delete. Format: - ``projects//locations//agents//webhooks/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 webhook.DeleteWebhookRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, webhook.DeleteWebhookRequest): - request = webhook.DeleteWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_webhook] - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "WebhooksClient", -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py deleted file mode 100644 index 5c10e717..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/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.dialogflowcx_v3.types import webhook - - -class ListWebhooksPager: - """A pager for iterating through ``list_webhooks`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` object, and - provides an ``__iter__`` method to iterate through its - ``webhooks`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWebhooks`` requests and continue to iterate - through the ``webhooks`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` - 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[..., webhook.ListWebhooksResponse], - request: webhook.ListWebhooksRequest, - response: webhook.ListWebhooksResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListWebhooksRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListWebhooksResponse): - 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 = webhook.ListWebhooksRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[webhook.ListWebhooksResponse]: - 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[webhook.Webhook]: - for page in self.pages: - yield from page.webhooks - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWebhooksAsyncPager: - """A pager for iterating through ``list_webhooks`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``webhooks`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWebhooks`` requests and continue to iterate - through the ``webhooks`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3.types.ListWebhooksResponse` - 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[webhook.ListWebhooksResponse]], - request: webhook.ListWebhooksRequest, - response: webhook.ListWebhooksResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3.types.ListWebhooksRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3.types.ListWebhooksResponse): - 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 = webhook.ListWebhooksRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[webhook.ListWebhooksResponse]: - 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[webhook.Webhook]: - async def async_generator(): - async for page in self.pages: - for response in page.webhooks: - 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/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py deleted file mode 100644 index 6006a6e7..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/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 WebhooksTransport -from .grpc import WebhooksGrpcTransport -from .grpc_asyncio import WebhooksGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WebhooksTransport]] -_transport_registry['grpc'] = WebhooksGrpcTransport -_transport_registry['grpc_asyncio'] = WebhooksGrpcAsyncIOTransport - -__all__ = ( - 'WebhooksTransport', - 'WebhooksGrpcTransport', - 'WebhooksGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py deleted file mode 100644 index 65512411..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/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.dialogflowcx_v3.types import webhook -from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook -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-dialogflowcx', - ).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 WebhooksTransport(abc.ABC): - """Abstract transport class for Webhooks.""" - - 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_webhooks: gapic_v1.method.wrap_method( - self.list_webhooks, - default_timeout=None, - client_info=client_info, - ), - self.get_webhook: gapic_v1.method.wrap_method( - self.get_webhook, - default_timeout=None, - client_info=client_info, - ), - self.create_webhook: gapic_v1.method.wrap_method( - self.create_webhook, - default_timeout=None, - client_info=client_info, - ), - self.update_webhook: gapic_v1.method.wrap_method( - self.update_webhook, - default_timeout=None, - client_info=client_info, - ), - self.delete_webhook: gapic_v1.method.wrap_method( - self.delete_webhook, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_webhooks(self) -> Callable[ - [webhook.ListWebhooksRequest], - Union[ - webhook.ListWebhooksResponse, - Awaitable[webhook.ListWebhooksResponse] - ]]: - raise NotImplementedError() - - @property - def get_webhook(self) -> Callable[ - [webhook.GetWebhookRequest], - Union[ - webhook.Webhook, - Awaitable[webhook.Webhook] - ]]: - raise NotImplementedError() - - @property - def create_webhook(self) -> Callable[ - [gcdc_webhook.CreateWebhookRequest], - Union[ - gcdc_webhook.Webhook, - Awaitable[gcdc_webhook.Webhook] - ]]: - raise NotImplementedError() - - @property - def update_webhook(self) -> Callable[ - [gcdc_webhook.UpdateWebhookRequest], - Union[ - gcdc_webhook.Webhook, - Awaitable[gcdc_webhook.Webhook] - ]]: - raise NotImplementedError() - - @property - def delete_webhook(self) -> Callable[ - [webhook.DeleteWebhookRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'WebhooksTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py deleted file mode 100644 index 34c40fc6..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/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.dialogflowcx_v3.types import webhook -from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook -from google.protobuf import empty_pb2 # type: ignore -from .base import WebhooksTransport, DEFAULT_CLIENT_INFO - - -class WebhooksGrpcTransport(WebhooksTransport): - """gRPC backend transport for Webhooks. - - Service for managing - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. - - 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_webhooks(self) -> Callable[ - [webhook.ListWebhooksRequest], - webhook.ListWebhooksResponse]: - r"""Return a callable for the list webhooks method over gRPC. - - Returns the list of all webhooks in the specified - agent. - - Returns: - Callable[[~.ListWebhooksRequest], - ~.ListWebhooksResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_webhooks' not in self._stubs: - self._stubs['list_webhooks'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Webhooks/ListWebhooks', - request_serializer=webhook.ListWebhooksRequest.serialize, - response_deserializer=webhook.ListWebhooksResponse.deserialize, - ) - return self._stubs['list_webhooks'] - - @property - def get_webhook(self) -> Callable[ - [webhook.GetWebhookRequest], - webhook.Webhook]: - r"""Return a callable for the get webhook method over gRPC. - - Retrieves the specified webhook. - - Returns: - Callable[[~.GetWebhookRequest], - ~.Webhook]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_webhook' not in self._stubs: - self._stubs['get_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Webhooks/GetWebhook', - request_serializer=webhook.GetWebhookRequest.serialize, - response_deserializer=webhook.Webhook.deserialize, - ) - return self._stubs['get_webhook'] - - @property - def create_webhook(self) -> Callable[ - [gcdc_webhook.CreateWebhookRequest], - gcdc_webhook.Webhook]: - r"""Return a callable for the create webhook method over gRPC. - - Creates a webhook in the specified agent. - - Returns: - Callable[[~.CreateWebhookRequest], - ~.Webhook]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_webhook' not in self._stubs: - self._stubs['create_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Webhooks/CreateWebhook', - request_serializer=gcdc_webhook.CreateWebhookRequest.serialize, - response_deserializer=gcdc_webhook.Webhook.deserialize, - ) - return self._stubs['create_webhook'] - - @property - def update_webhook(self) -> Callable[ - [gcdc_webhook.UpdateWebhookRequest], - gcdc_webhook.Webhook]: - r"""Return a callable for the update webhook method over gRPC. - - Updates the specified webhook. - - Returns: - Callable[[~.UpdateWebhookRequest], - ~.Webhook]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_webhook' not in self._stubs: - self._stubs['update_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Webhooks/UpdateWebhook', - request_serializer=gcdc_webhook.UpdateWebhookRequest.serialize, - response_deserializer=gcdc_webhook.Webhook.deserialize, - ) - return self._stubs['update_webhook'] - - @property - def delete_webhook(self) -> Callable[ - [webhook.DeleteWebhookRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete webhook method over gRPC. - - Deletes the specified webhook. - - Returns: - Callable[[~.DeleteWebhookRequest], - ~.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_webhook' not in self._stubs: - self._stubs['delete_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Webhooks/DeleteWebhook', - request_serializer=webhook.DeleteWebhookRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_webhook'] - - -__all__ = ( - 'WebhooksGrpcTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py deleted file mode 100644 index 83099cd0..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/services/webhooks/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.dialogflowcx_v3.types import webhook -from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook -from google.protobuf import empty_pb2 # type: ignore -from .base import WebhooksTransport, DEFAULT_CLIENT_INFO -from .grpc import WebhooksGrpcTransport - - -class WebhooksGrpcAsyncIOTransport(WebhooksTransport): - """gRPC AsyncIO backend transport for Webhooks. - - Service for managing - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook]. - - 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_webhooks(self) -> Callable[ - [webhook.ListWebhooksRequest], - Awaitable[webhook.ListWebhooksResponse]]: - r"""Return a callable for the list webhooks method over gRPC. - - Returns the list of all webhooks in the specified - agent. - - Returns: - Callable[[~.ListWebhooksRequest], - Awaitable[~.ListWebhooksResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_webhooks' not in self._stubs: - self._stubs['list_webhooks'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Webhooks/ListWebhooks', - request_serializer=webhook.ListWebhooksRequest.serialize, - response_deserializer=webhook.ListWebhooksResponse.deserialize, - ) - return self._stubs['list_webhooks'] - - @property - def get_webhook(self) -> Callable[ - [webhook.GetWebhookRequest], - Awaitable[webhook.Webhook]]: - r"""Return a callable for the get webhook method over gRPC. - - Retrieves the specified webhook. - - Returns: - Callable[[~.GetWebhookRequest], - Awaitable[~.Webhook]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_webhook' not in self._stubs: - self._stubs['get_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Webhooks/GetWebhook', - request_serializer=webhook.GetWebhookRequest.serialize, - response_deserializer=webhook.Webhook.deserialize, - ) - return self._stubs['get_webhook'] - - @property - def create_webhook(self) -> Callable[ - [gcdc_webhook.CreateWebhookRequest], - Awaitable[gcdc_webhook.Webhook]]: - r"""Return a callable for the create webhook method over gRPC. - - Creates a webhook in the specified agent. - - Returns: - Callable[[~.CreateWebhookRequest], - Awaitable[~.Webhook]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_webhook' not in self._stubs: - self._stubs['create_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Webhooks/CreateWebhook', - request_serializer=gcdc_webhook.CreateWebhookRequest.serialize, - response_deserializer=gcdc_webhook.Webhook.deserialize, - ) - return self._stubs['create_webhook'] - - @property - def update_webhook(self) -> Callable[ - [gcdc_webhook.UpdateWebhookRequest], - Awaitable[gcdc_webhook.Webhook]]: - r"""Return a callable for the update webhook method over gRPC. - - Updates the specified webhook. - - Returns: - Callable[[~.UpdateWebhookRequest], - Awaitable[~.Webhook]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_webhook' not in self._stubs: - self._stubs['update_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Webhooks/UpdateWebhook', - request_serializer=gcdc_webhook.UpdateWebhookRequest.serialize, - response_deserializer=gcdc_webhook.Webhook.deserialize, - ) - return self._stubs['update_webhook'] - - @property - def delete_webhook(self) -> Callable[ - [webhook.DeleteWebhookRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete webhook method over gRPC. - - Deletes the specified webhook. - - Returns: - Callable[[~.DeleteWebhookRequest], - 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_webhook' not in self._stubs: - self._stubs['delete_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3.Webhooks/DeleteWebhook', - request_serializer=webhook.DeleteWebhookRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_webhook'] - - -__all__ = ( - 'WebhooksGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.py deleted file mode 100644 index 98d63df7..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/__init__.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. -# -from .agent import ( - Agent, - AgentValidationResult, - CreateAgentRequest, - DeleteAgentRequest, - ExportAgentRequest, - ExportAgentResponse, - GetAgentRequest, - GetAgentValidationResultRequest, - ListAgentsRequest, - ListAgentsResponse, - RestoreAgentRequest, - SpeechToTextSettings, - UpdateAgentRequest, - ValidateAgentRequest, -) -from .audio_config import ( - InputAudioConfig, - OutputAudioConfig, - SpeechWordInfo, - SynthesizeSpeechConfig, - VoiceSelectionParams, - AudioEncoding, - OutputAudioEncoding, - SpeechModelVariant, - SsmlVoiceGender, -) -from .entity_type import ( - CreateEntityTypeRequest, - DeleteEntityTypeRequest, - EntityType, - GetEntityTypeRequest, - ListEntityTypesRequest, - ListEntityTypesResponse, - UpdateEntityTypeRequest, -) -from .environment import ( - CreateEnvironmentRequest, - DeleteEnvironmentRequest, - Environment, - GetEnvironmentRequest, - ListEnvironmentsRequest, - ListEnvironmentsResponse, - LookupEnvironmentHistoryRequest, - LookupEnvironmentHistoryResponse, - UpdateEnvironmentRequest, -) -from .experiment import ( - CreateExperimentRequest, - DeleteExperimentRequest, - Experiment, - GetExperimentRequest, - ListExperimentsRequest, - ListExperimentsResponse, - StartExperimentRequest, - StopExperimentRequest, - UpdateExperimentRequest, - VariantsHistory, - VersionVariants, -) -from .flow import ( - CreateFlowRequest, - DeleteFlowRequest, - ExportFlowRequest, - ExportFlowResponse, - Flow, - FlowValidationResult, - GetFlowRequest, - GetFlowValidationResultRequest, - ImportFlowRequest, - ImportFlowResponse, - ListFlowsRequest, - ListFlowsResponse, - NluSettings, - TrainFlowRequest, - UpdateFlowRequest, - ValidateFlowRequest, -) -from .fulfillment import ( - Fulfillment, -) -from .intent import ( - CreateIntentRequest, - DeleteIntentRequest, - GetIntentRequest, - Intent, - ListIntentsRequest, - ListIntentsResponse, - UpdateIntentRequest, - IntentView, -) -from .page import ( - CreatePageRequest, - DeletePageRequest, - EventHandler, - Form, - GetPageRequest, - ListPagesRequest, - ListPagesResponse, - Page, - TransitionRoute, - UpdatePageRequest, -) -from .response_message import ( - ResponseMessage, -) -from .security_settings import ( - CreateSecuritySettingsRequest, - DeleteSecuritySettingsRequest, - GetSecuritySettingsRequest, - ListSecuritySettingsRequest, - ListSecuritySettingsResponse, - SecuritySettings, - UpdateSecuritySettingsRequest, -) -from .session import ( - AudioInput, - DetectIntentRequest, - DetectIntentResponse, - DtmfInput, - EventInput, - FulfillIntentRequest, - FulfillIntentResponse, - IntentInput, - Match, - MatchIntentRequest, - MatchIntentResponse, - QueryInput, - QueryParameters, - QueryResult, - SentimentAnalysisResult, - StreamingDetectIntentRequest, - StreamingDetectIntentResponse, - StreamingRecognitionResult, - TextInput, -) -from .session_entity_type import ( - CreateSessionEntityTypeRequest, - DeleteSessionEntityTypeRequest, - GetSessionEntityTypeRequest, - ListSessionEntityTypesRequest, - ListSessionEntityTypesResponse, - SessionEntityType, - UpdateSessionEntityTypeRequest, -) -from .test_case import ( - BatchDeleteTestCasesRequest, - BatchRunTestCasesMetadata, - BatchRunTestCasesRequest, - BatchRunTestCasesResponse, - CalculateCoverageRequest, - CalculateCoverageResponse, - ConversationTurn, - CreateTestCaseRequest, - ExportTestCasesMetadata, - ExportTestCasesRequest, - ExportTestCasesResponse, - GetTestCaseRequest, - GetTestCaseResultRequest, - ImportTestCasesMetadata, - ImportTestCasesRequest, - ImportTestCasesResponse, - IntentCoverage, - ListTestCaseResultsRequest, - ListTestCaseResultsResponse, - ListTestCasesRequest, - ListTestCasesResponse, - RunTestCaseMetadata, - RunTestCaseRequest, - RunTestCaseResponse, - TestCase, - TestCaseError, - TestCaseResult, - TestConfig, - TestError, - TestRunDifference, - TransitionCoverage, - TransitionRouteGroupCoverage, - UpdateTestCaseRequest, - TestResult, -) -from .transition_route_group import ( - CreateTransitionRouteGroupRequest, - DeleteTransitionRouteGroupRequest, - GetTransitionRouteGroupRequest, - ListTransitionRouteGroupsRequest, - ListTransitionRouteGroupsResponse, - TransitionRouteGroup, - UpdateTransitionRouteGroupRequest, -) -from .validation_message import ( - ResourceName, - ValidationMessage, -) -from .version import ( - CreateVersionOperationMetadata, - CreateVersionRequest, - DeleteVersionRequest, - GetVersionRequest, - ListVersionsRequest, - ListVersionsResponse, - LoadVersionRequest, - UpdateVersionRequest, - Version, -) -from .webhook import ( - CreateWebhookRequest, - DeleteWebhookRequest, - GetWebhookRequest, - ListWebhooksRequest, - ListWebhooksResponse, - PageInfo, - SessionInfo, - UpdateWebhookRequest, - Webhook, - WebhookRequest, - WebhookResponse, -) - -__all__ = ( - 'Agent', - 'AgentValidationResult', - 'CreateAgentRequest', - 'DeleteAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'GetAgentRequest', - 'GetAgentValidationResultRequest', - 'ListAgentsRequest', - 'ListAgentsResponse', - 'RestoreAgentRequest', - 'SpeechToTextSettings', - 'UpdateAgentRequest', - 'ValidateAgentRequest', - 'InputAudioConfig', - 'OutputAudioConfig', - 'SpeechWordInfo', - 'SynthesizeSpeechConfig', - 'VoiceSelectionParams', - 'AudioEncoding', - 'OutputAudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'CreateEntityTypeRequest', - 'DeleteEntityTypeRequest', - 'EntityType', - 'GetEntityTypeRequest', - 'ListEntityTypesRequest', - 'ListEntityTypesResponse', - 'UpdateEntityTypeRequest', - 'CreateEnvironmentRequest', - 'DeleteEnvironmentRequest', - 'Environment', - 'GetEnvironmentRequest', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LookupEnvironmentHistoryRequest', - 'LookupEnvironmentHistoryResponse', - 'UpdateEnvironmentRequest', - 'CreateExperimentRequest', - 'DeleteExperimentRequest', - 'Experiment', - 'GetExperimentRequest', - 'ListExperimentsRequest', - 'ListExperimentsResponse', - 'StartExperimentRequest', - 'StopExperimentRequest', - 'UpdateExperimentRequest', - 'VariantsHistory', - 'VersionVariants', - 'CreateFlowRequest', - 'DeleteFlowRequest', - 'ExportFlowRequest', - 'ExportFlowResponse', - 'Flow', - 'FlowValidationResult', - 'GetFlowRequest', - 'GetFlowValidationResultRequest', - 'ImportFlowRequest', - 'ImportFlowResponse', - 'ListFlowsRequest', - 'ListFlowsResponse', - 'NluSettings', - 'TrainFlowRequest', - 'UpdateFlowRequest', - 'ValidateFlowRequest', - 'Fulfillment', - 'CreateIntentRequest', - 'DeleteIntentRequest', - 'GetIntentRequest', - 'Intent', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'UpdateIntentRequest', - 'IntentView', - 'CreatePageRequest', - 'DeletePageRequest', - 'EventHandler', - 'Form', - 'GetPageRequest', - 'ListPagesRequest', - 'ListPagesResponse', - 'Page', - 'TransitionRoute', - 'UpdatePageRequest', - 'ResponseMessage', - 'CreateSecuritySettingsRequest', - 'DeleteSecuritySettingsRequest', - 'GetSecuritySettingsRequest', - 'ListSecuritySettingsRequest', - 'ListSecuritySettingsResponse', - 'SecuritySettings', - 'UpdateSecuritySettingsRequest', - 'AudioInput', - 'DetectIntentRequest', - 'DetectIntentResponse', - 'DtmfInput', - 'EventInput', - 'FulfillIntentRequest', - 'FulfillIntentResponse', - 'IntentInput', - 'Match', - 'MatchIntentRequest', - 'MatchIntentResponse', - 'QueryInput', - 'QueryParameters', - 'QueryResult', - 'SentimentAnalysisResult', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'TextInput', - 'CreateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - 'GetSessionEntityTypeRequest', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'SessionEntityType', - 'UpdateSessionEntityTypeRequest', - 'BatchDeleteTestCasesRequest', - 'BatchRunTestCasesMetadata', - 'BatchRunTestCasesRequest', - 'BatchRunTestCasesResponse', - 'CalculateCoverageRequest', - 'CalculateCoverageResponse', - 'ConversationTurn', - 'CreateTestCaseRequest', - 'ExportTestCasesMetadata', - 'ExportTestCasesRequest', - 'ExportTestCasesResponse', - 'GetTestCaseRequest', - 'GetTestCaseResultRequest', - 'ImportTestCasesMetadata', - 'ImportTestCasesRequest', - 'ImportTestCasesResponse', - 'IntentCoverage', - 'ListTestCaseResultsRequest', - 'ListTestCaseResultsResponse', - 'ListTestCasesRequest', - 'ListTestCasesResponse', - 'RunTestCaseMetadata', - 'RunTestCaseRequest', - 'RunTestCaseResponse', - 'TestCase', - 'TestCaseError', - 'TestCaseResult', - 'TestConfig', - 'TestError', - 'TestRunDifference', - 'TransitionCoverage', - 'TransitionRouteGroupCoverage', - 'UpdateTestCaseRequest', - 'TestResult', - 'CreateTransitionRouteGroupRequest', - 'DeleteTransitionRouteGroupRequest', - 'GetTransitionRouteGroupRequest', - 'ListTransitionRouteGroupsRequest', - 'ListTransitionRouteGroupsResponse', - 'TransitionRouteGroup', - 'UpdateTransitionRouteGroupRequest', - 'ResourceName', - 'ValidationMessage', - 'CreateVersionOperationMetadata', - 'CreateVersionRequest', - 'DeleteVersionRequest', - 'GetVersionRequest', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'LoadVersionRequest', - 'UpdateVersionRequest', - 'Version', - 'CreateWebhookRequest', - 'DeleteWebhookRequest', - 'GetWebhookRequest', - 'ListWebhooksRequest', - 'ListWebhooksResponse', - 'PageInfo', - 'SessionInfo', - 'UpdateWebhookRequest', - 'Webhook', - 'WebhookRequest', - 'WebhookResponse', -) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py deleted file mode 100644 index 67a58714..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/agent.py +++ /dev/null @@ -1,491 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import flow -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'SpeechToTextSettings', - 'Agent', - 'ListAgentsRequest', - 'ListAgentsResponse', - 'GetAgentRequest', - 'CreateAgentRequest', - 'UpdateAgentRequest', - 'DeleteAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'RestoreAgentRequest', - 'ValidateAgentRequest', - 'GetAgentValidationResultRequest', - 'AgentValidationResult', - }, -) - - -class SpeechToTextSettings(proto.Message): - r"""Settings related to speech recognition. - Attributes: - enable_speech_adaptation (bool): - Whether to use speech adaptation for speech - recognition. - """ - - enable_speech_adaptation = proto.Field( - proto.BOOL, - number=1, - ) - - -class Agent(proto.Message): - r"""Agents are best described as Natural Language Understanding (NLU) - modules that transform user requests into actionable data. You can - include agents in your app, product, or service to determine user - intent and respond to the user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3.Intent], [Entity - Types][google.cloud.dialogflow.cx.v3.EntityType], - [Flows][google.cloud.dialogflow.cx.v3.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3.Webhook], and so on to - manage the conversation flows.. - - Attributes: - name (str): - The unique identifier of the agent. Required for the - [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent] - method. - [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent] - populates the name automatically. Format: - ``projects//locations//agents/``. - display_name (str): - Required. The human-readable name of the - agent, unique within the location. - default_language_code (str): - Immutable. 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 - [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent] - method. - supported_language_codes (Sequence[str]): - The list of all languages supported by the agent (except for - the ``default_language_code``). - time_zone (str): - Required. The time zone of the agent from the `time zone - database `__, e.g., - America/New_York, Europe/Paris. - description (str): - The description of the agent. The maximum - length is 500 characters. If exceeded, the - request is rejected. - avatar_uri (str): - The URI of the agent's avatar. Avatars are used throughout - the Dialogflow console and in the self-hosted `Web - Demo `__ - integration. - speech_to_text_settings (google.cloud.dialogflowcx_v3.types.SpeechToTextSettings): - Speech recognition related settings. - start_flow (str): - Immutable. Name of the start flow in this agent. A start - flow will be automatically created when the agent is - created, and can only be deleted by deleting the agent. - Format: - ``projects//locations//agents//flows/``. - security_settings (str): - Name of the - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] - reference for the agent. Format: - ``projects//locations//securitySettings/``. - enable_stackdriver_logging (bool): - Indicates if stackdriver logging is enabled - for the agent. - enable_spell_correction (bool): - Indicates if automatic spell correction is - enabled in detect intent requests. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - default_language_code = proto.Field( - proto.STRING, - number=3, - ) - supported_language_codes = proto.RepeatedField( - proto.STRING, - number=4, - ) - time_zone = proto.Field( - proto.STRING, - number=5, - ) - description = proto.Field( - proto.STRING, - number=6, - ) - avatar_uri = proto.Field( - proto.STRING, - number=7, - ) - speech_to_text_settings = proto.Field( - proto.MESSAGE, - number=13, - message='SpeechToTextSettings', - ) - start_flow = proto.Field( - proto.STRING, - number=16, - ) - security_settings = proto.Field( - proto.STRING, - number=17, - ) - enable_stackdriver_logging = proto.Field( - proto.BOOL, - number=18, - ) - enable_spell_correction = proto.Field( - proto.BOOL, - number=20, - ) - - -class ListAgentsRequest(proto.Message): - r"""The request message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. - - Attributes: - parent (str): - Required. The location to list all agents for. 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 ListAgentsResponse(proto.Message): - r"""The response message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3.Agents.ListAgents]. - - Attributes: - agents (Sequence[google.cloud.dialogflowcx_v3.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 GetAgentRequest(proto.Message): - r"""The request message for - [Agents.GetAgent][google.cloud.dialogflow.cx.v3.Agents.GetAgent]. - - Attributes: - name (str): - Required. The name of the agent. Format: - ``projects//locations//agents/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateAgentRequest(proto.Message): - r"""The request message for - [Agents.CreateAgent][google.cloud.dialogflow.cx.v3.Agents.CreateAgent]. - - Attributes: - parent (str): - Required. The location to create a agent for. Format: - ``projects//locations/``. - agent (google.cloud.dialogflowcx_v3.types.Agent): - Required. The agent to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - agent = proto.Field( - proto.MESSAGE, - number=2, - message='Agent', - ) - - -class UpdateAgentRequest(proto.Message): - r"""The request message for - [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent]. - - Attributes: - agent (google.cloud.dialogflowcx_v3.types.Agent): - Required. The agent to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The mask to control which fields get updated. - If the mask is not present, all fields will be - 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.cx.v3.Agents.DeleteAgent]. - - Attributes: - name (str): - Required. The name of the agent to delete. Format: - ``projects//locations//agents/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ExportAgentRequest(proto.Message): - r"""The request message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.Agents.ExportAgent]. - - Attributes: - name (str): - Required. The name of the agent to export. Format: - ``projects//locations//agents/``. - 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. - environment (str): - Optional. Environment name. If not set, draft environment is - assumed. Format: - ``projects//locations//agents//environments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - agent_uri = proto.Field( - proto.STRING, - number=2, - ) - environment = proto.Field( - proto.STRING, - number=5, - ) - - -class ExportAgentResponse(proto.Message): - r"""The response message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3.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][google.cloud.dialogflow.cx.v3.ExportAgentRequest]. - agent_content (bytes): - Uncompressed raw byte content for agent. - """ - - agent_uri = proto.Field( - proto.STRING, - number=1, - oneof='agent', - ) - agent_content = proto.Field( - proto.BYTES, - number=2, - oneof='agent', - ) - - -class RestoreAgentRequest(proto.Message): - r"""The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3.Agents.RestoreAgent]. - - Attributes: - name (str): - Required. The name of the agent to restore into. Format: - ``projects//locations//agents/``. - agent_uri (str): - The `Google Cloud - Storage `__ URI to - restore agent from. The format of this URI must be - ``gs:///``. - agent_content (bytes): - Uncompressed raw byte content for agent. - restore_option (google.cloud.dialogflowcx_v3.types.RestoreAgentRequest.RestoreOption): - Agent restore mode. If not specified, ``KEEP`` is assumed. - """ - class RestoreOption(proto.Enum): - r"""Restore option.""" - RESTORE_OPTION_UNSPECIFIED = 0 - KEEP = 1 - FALLBACK = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - agent_uri = proto.Field( - proto.STRING, - number=2, - oneof='agent', - ) - agent_content = proto.Field( - proto.BYTES, - number=3, - oneof='agent', - ) - restore_option = proto.Field( - proto.ENUM, - number=5, - enum=RestoreOption, - ) - - -class ValidateAgentRequest(proto.Message): - r"""The request message for - [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3.Agents.ValidateAgent]. - - Attributes: - name (str): - Required. The agent to validate. Format: - ``projects//locations//agents/``. - language_code (str): - If not specified, the agent's default - language is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class GetAgentValidationResultRequest(proto.Message): - r"""The request message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. - - Attributes: - name (str): - Required. The agent name. Format: - ``projects//locations//agents//validationResult``. - language_code (str): - If not specified, the agent's default - language is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class AgentValidationResult(proto.Message): - r"""The response message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3.Agents.GetAgentValidationResult]. - - Attributes: - name (str): - The unique identifier of the agent validation result. - Format: - ``projects//locations//agents//validationResult``. - flow_validation_results (Sequence[google.cloud.dialogflowcx_v3.types.FlowValidationResult]): - Contains all flow validation results. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - flow_validation_results = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=flow.FlowValidationResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.py deleted file mode 100644 index 79422752..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/audio_config.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 proto # type: ignore - -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'AudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'OutputAudioEncoding', - 'SpeechWordInfo', - 'InputAudioConfig', - 'VoiceSelectionParams', - 'SynthesizeSpeechConfig', - 'OutputAudioConfig', - }, -) - - -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.cx.v3.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 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.dialogflowcx_v3.types.AudioEncoding): - Required. Audio encoding of the audio content - to process. - sample_rate_hertz (int): - Sample rate (in Hertz) of the audio content sent in the - query. Refer to `Cloud Speech API - documentation `__ - for more details. - enable_word_info (bool): - Optional. If ``true``, Dialogflow returns - [SpeechWordInfo][google.cloud.dialogflow.cx.v3.SpeechWordInfo] - in - [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3.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]): - Optional. 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. - model (str): - Optional. 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.dialogflowcx_v3.types.SpeechModelVariant): - Optional. Which variant of the [Speech - model][google.cloud.dialogflow.cx.v3.InputAudioConfig.model] - to use. - single_utterance (bool): - Optional. 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. - """ - - audio_encoding = proto.Field( - proto.ENUM, - number=1, - enum='AudioEncoding', - ) - sample_rate_hertz = proto.Field( - proto.INT32, - number=2, - ) - enable_word_info = proto.Field( - proto.BOOL, - number=13, - ) - phrase_hints = proto.RepeatedField( - proto.STRING, - number=4, - ) - model = proto.Field( - proto.STRING, - number=7, - ) - model_variant = proto.Field( - proto.ENUM, - number=10, - enum='SpeechModelVariant', - ) - single_utterance = proto.Field( - proto.BOOL, - number=8, - ) - - -class VoiceSelectionParams(proto.Message): - r"""Description of which voice to use for speech synthesis. - Attributes: - name (str): - Optional. The name of the voice. If not set, the service - will choose a voice based on the other parameters such as - language_code and - [ssml_gender][google.cloud.dialogflow.cx.v3.VoiceSelectionParams.ssml_gender]. - - For the list of available voices, please refer to `Supported - voices and - languages `__. - ssml_gender (google.cloud.dialogflowcx_v3.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.cx.v3.VoiceSelectionParams.name]. - Note that this is only a preference, not requirement. If a - voice of the appropriate gender is not available, the - synthesizer substitutes 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.dialogflowcx_v3.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. - - Attributes: - audio_encoding (google.cloud.dialogflowcx_v3.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_config (google.cloud.dialogflowcx_v3.types.SynthesizeSpeechConfig): - Optional. 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', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py deleted file mode 100644 index 8aea5942..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/entity_type.py +++ /dev/null @@ -1,425 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cx.v3', - manifest={ - 'EntityType', - 'ListEntityTypesRequest', - 'ListEntityTypesResponse', - 'GetEntityTypeRequest', - 'CreateEntityTypeRequest', - 'UpdateEntityTypeRequest', - 'DeleteEntityTypeRequest', - }, -) - - -class EntityType(proto.Message): - r"""Entities are extracted from user input and represent parameters that - are meaningful to your application. For example, a date range, a - proper name such as a geographic location or landmark, and so on. - Entities represent actionable data for your application. - - When you define an entity, you can also include synonyms that all - map to that entity. For example, "soft drink", "soda", "pop", and so - on. - - There are three types of entities: - - - **System** - entities that are defined by the Dialogflow API for - common data types such as date, time, currency, and so on. A - system entity is represented by the ``EntityType`` type. - - - **Custom** - entities that are defined by you that represent - actionable data that is meaningful to your application. For - example, you could define a ``pizza.sauce`` entity for red or - white pizza sauce, a ``pizza.cheese`` entity for the different - types of cheese on a pizza, a ``pizza.topping`` entity for - different toppings, and so on. A custom entity is represented by - the ``EntityType`` type. - - - **User** - entities that are built for an individual user such as - favorites, preferences, playlists, and so on. A user entity is - represented by the - [SessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityType] - type. - - For more information about entity types, see the `Dialogflow - documentation `__. - - Attributes: - name (str): - The unique identifier of the entity type. Required for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3.EntityTypes.UpdateEntityType]. - Format: - ``projects//locations//agents//entityTypes/``. - display_name (str): - Required. The human-readable name of the - entity type, unique within the agent. - kind (google.cloud.dialogflowcx_v3.types.EntityType.Kind): - Required. Indicates the kind of entity type. - auto_expansion_mode (google.cloud.dialogflowcx_v3.types.EntityType.AutoExpansionMode): - Indicates whether the entity type can be - automatically expanded. - entities (Sequence[google.cloud.dialogflowcx_v3.types.EntityType.Entity]): - The collection of entity entries associated - with the entity type. - excluded_phrases (Sequence[google.cloud.dialogflowcx_v3.types.EntityType.ExcludedPhrase]): - Collection of exceptional words and phrases that shouldn't - be matched. For example, if you have a size entity type with - entry ``giant``\ (an adjective), you might consider adding - ``giants``\ (a noun) as an exclusion. If the kind of entity - type is ``KIND_MAP``, then the phrases specified by entities - and excluded phrases should be mutually exclusive. - enable_fuzzy_extraction (bool): - Enables fuzzy entity extraction during - classification. - redact (bool): - Indicates whether parameters of the entity - type should be redacted in log. If redaction is - enabled, page parameters and intent parameters - referring to the entity type will be replaced by - parameter name when logging. - """ - 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 canonical 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, - ) - - class ExcludedPhrase(proto.Message): - r"""An excluded entity phrase that should not be matched. - Attributes: - value (str): - Required. The word or phrase to be excluded. - """ - - value = proto.Field( - proto.STRING, - number=1, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - kind = proto.Field( - proto.ENUM, - number=3, - enum=Kind, - ) - auto_expansion_mode = proto.Field( - proto.ENUM, - number=4, - enum=AutoExpansionMode, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Entity, - ) - excluded_phrases = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=ExcludedPhrase, - ) - enable_fuzzy_extraction = proto.Field( - proto.BOOL, - number=7, - ) - redact = proto.Field( - proto.BOOL, - number=9, - ) - - -class ListEntityTypesRequest(proto.Message): - r"""The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3.EntityTypes.ListEntityTypes]. - - Attributes: - parent (str): - Required. The agent to list all entity types for. Format: - ``projects//locations//agents/``. - language_code (str): - The language to list entity types for. The following fields - are language dependent: - - - ``EntityType.entities.value`` - - ``EntityType.entities.synonyms`` - - ``EntityType.excluded_phrases.value`` - - 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. - 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, - ) - 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.cx.v3.EntityTypes.ListEntityTypes]. - - Attributes: - entity_types (Sequence[google.cloud.dialogflowcx_v3.types.EntityType]): - The list of 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.cx.v3.EntityTypes.GetEntityType]. - - Attributes: - name (str): - Required. The name of the entity type. Format: - ``projects//locations//agents//entityTypes/``. - language_code (str): - The language to retrieve the entity type for. The following - fields are language dependent: - - - ``EntityType.entities.value`` - - ``EntityType.entities.synonyms`` - - ``EntityType.excluded_phrases.value`` - - 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. - """ - - 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.cx.v3.EntityTypes.CreateEntityType]. - - Attributes: - parent (str): - Required. The agent to create a entity type for. Format: - ``projects//locations//agents/``. - entity_type (google.cloud.dialogflowcx_v3.types.EntityType): - Required. The entity type to create. - language_code (str): - The language of the following fields in ``entity_type``: - - - ``EntityType.entities.value`` - - ``EntityType.entities.synonyms`` - - ``EntityType.excluded_phrases.value`` - - 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, - ) - 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.cx.v3.EntityTypes.UpdateEntityType]. - - Attributes: - entity_type (google.cloud.dialogflowcx_v3.types.EntityType): - Required. The entity type to update. - language_code (str): - The language of the following fields in ``entity_type``: - - - ``EntityType.entities.value`` - - ``EntityType.entities.synonyms`` - - ``EntityType.excluded_phrases.value`` - - 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. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.cx.v3.EntityTypes.DeleteEntityType]. - - Attributes: - name (str): - Required. The name of the entity type to delete. Format: - ``projects//locations//agents//entityTypes/``. - force (bool): - This field has no effect for entity type not being used. For - entity types that are used by intents or pages: - - - If ``force`` is set to false, an error will be returned - with message indicating the referencing resources. - - If ``force`` is set to true, Dialogflow will remove the - entity type, as well as any references to the entity type - (i.e. Page - [parameter][google.cloud.dialogflow.cx.v3.Form.Parameter] - of the entity type will be changed to '@sys.any' and - intent - [parameter][google.cloud.dialogflow.cx.v3.Intent.Parameter] - of the entity type will be removed). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.py deleted file mode 100644 index 9736600a..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/environment.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 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.cx.v3', - manifest={ - 'Environment', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'GetEnvironmentRequest', - 'CreateEnvironmentRequest', - 'UpdateEnvironmentRequest', - 'DeleteEnvironmentRequest', - 'LookupEnvironmentHistoryRequest', - 'LookupEnvironmentHistoryResponse', - }, -) - - -class Environment(proto.Message): - r"""Represents an environment for an agent. 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. - - Attributes: - name (str): - The name of the environment. Format: - ``projects//locations//agents//environments/``. - display_name (str): - Required. The human-readable name of the - environment (unique in an agent). Limit of 64 - characters. - description (str): - The human-readable description of the - environment. The maximum length is 500 - characters. If exceeded, the request is - rejected. - version_configs (Sequence[google.cloud.dialogflowcx_v3.types.Environment.VersionConfig]): - Required. A list of configurations for flow versions. You - should include version configs for all flows that are - reachable from [``Start Flow``][Agent.start_flow] in the - agent. Otherwise, an error will be returned. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Update time of this environment. - """ - - class VersionConfig(proto.Message): - r"""Configuration for the version. - Attributes: - version (str): - Required. Format: projects//locations//agents//flows//versions/. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - version_configs = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=VersionConfig, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -class ListEnvironmentsRequest(proto.Message): - r"""The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. - - Attributes: - parent (str): - Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] - to list all environments for. Format: - ``projects//locations//agents/``. - page_size (int): - The maximum number of items to return in a - single page. By default 20 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 ListEnvironmentsResponse(proto.Message): - r"""The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3.Environments.ListEnvironments]. - - Attributes: - environments (Sequence[google.cloud.dialogflowcx_v3.types.Environment]): - The list of environments. There will be a maximum number of - items returned based on the page_size field in the request. - The list may in some cases be empty or contain fewer entries - than page_size even if this isn't the last page. - 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.cx.v3.Environments.GetEnvironment]. - - Attributes: - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - Format: - ``projects//locations//agents//environments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3.Environments.CreateEnvironment]. - - Attributes: - parent (str): - Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] - to create an - [Environment][google.cloud.dialogflow.cx.v3.Environment] - for. Format: - ``projects//locations//agents/``. - environment (google.cloud.dialogflowcx_v3.types.Environment): - Required. The environment to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - environment = proto.Field( - proto.MESSAGE, - number=2, - message='Environment', - ) - - -class UpdateEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3.Environments.UpdateEnvironment]. - - Attributes: - environment (google.cloud.dialogflowcx_v3.types.Environment): - Required. The environment to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields - get updated. - """ - - environment = proto.Field( - proto.MESSAGE, - number=1, - message='Environment', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3.Environments.DeleteEnvironment]. - - Attributes: - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment] to - delete. Format: - ``projects//locations//agents//environments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class LookupEnvironmentHistoryRequest(proto.Message): - r"""The request message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. - - Attributes: - name (str): - Required. Resource name of the environment to look up the - history for. Format: - ``projects//locations//agents//environments/``. - 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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class LookupEnvironmentHistoryResponse(proto.Message): - r"""The response message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3.Environments.LookupEnvironmentHistory]. - - Attributes: - environments (Sequence[google.cloud.dialogflowcx_v3.types.Environment]): - Represents a list of snapshots for an environment. Time of - the snapshots is stored in - [``update_time``][google.cloud.dialogflow.cx.v3.Environment.update_time]. - 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, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py deleted file mode 100644 index 5d1bfd1e..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/experiment.py +++ /dev/null @@ -1,568 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'Experiment', - 'VersionVariants', - 'VariantsHistory', - 'ListExperimentsRequest', - 'ListExperimentsResponse', - 'GetExperimentRequest', - 'CreateExperimentRequest', - 'UpdateExperimentRequest', - 'DeleteExperimentRequest', - 'StartExperimentRequest', - 'StopExperimentRequest', - }, -) - - -class Experiment(proto.Message): - r"""Represents an experiment in an environment. - Attributes: - name (str): - The name of the experiment. - Format: projects//locations//agents//environments//experiments/.. - display_name (str): - Required. The human-readable name of the - experiment (unique in an environment). Limit of - 64 characters. - description (str): - The human-readable description of the - experiment. - state (google.cloud.dialogflowcx_v3.types.Experiment.State): - The current state of the experiment. - Transition triggered by - Expriments.StartExperiment: PENDING->RUNNING. - Transition triggered by - Expriments.CancelExperiment: PENDING->CANCELLED - or RUNNING->CANCELLED. - definition (google.cloud.dialogflowcx_v3.types.Experiment.Definition): - The definition of the experiment. - result (google.cloud.dialogflowcx_v3.types.Experiment.Result): - Inference result of the experiment. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Creation time of this experiment. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start time of this experiment. - end_time (google.protobuf.timestamp_pb2.Timestamp): - End time of this experiment. - last_update_time (google.protobuf.timestamp_pb2.Timestamp): - Last update time of this experiment. - experiment_length (google.protobuf.duration_pb2.Duration): - Maximum number of days to run the - experiment/rollout. If auto-rollout is not - enabled, default value and maximum will be 30 - days. If auto-rollout is enabled, default value - and maximum will be 6 days. - variants_history (Sequence[google.cloud.dialogflowcx_v3.types.VariantsHistory]): - The history of updates to the experiment - variants. - """ - class State(proto.Enum): - r"""The state of the experiment.""" - STATE_UNSPECIFIED = 0 - DRAFT = 1 - RUNNING = 2 - DONE = 3 - - class Definition(proto.Message): - r"""Definition of the experiment. - Attributes: - condition (str): - The condition defines which subset of sessions are selected - for this experiment. If not specified, all sessions are - eligible. E.g. "query_input.language_code=en" See the - `conditions - reference `__. - version_variants (google.cloud.dialogflowcx_v3.types.VersionVariants): - The flow versions as the variants of this - experiment. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - version_variants = proto.Field( - proto.MESSAGE, - number=2, - oneof='variants', - message='VersionVariants', - ) - - class Result(proto.Message): - r"""The inference result which includes an objective metric to - optimize and the confidence interval. - - Attributes: - version_metrics (Sequence[google.cloud.dialogflowcx_v3.types.Experiment.Result.VersionMetrics]): - Version variants and metrics. - last_update_time (google.protobuf.timestamp_pb2.Timestamp): - The last time the experiment's stats data was - updated. Will have default value if stats have - never been computed for this experiment. - """ - class MetricType(proto.Enum): - r"""Types of ratio-based metric for Dialogflow experiment.""" - METRIC_UNSPECIFIED = 0 - CONTAINED_SESSION_NO_CALLBACK_RATE = 1 - LIVE_AGENT_HANDOFF_RATE = 2 - CALLBACK_SESSION_RATE = 3 - ABANDONED_SESSION_RATE = 4 - SESSION_END_RATE = 5 - - class CountType(proto.Enum): - r"""Types of count-based metric for Dialogflow experiment.""" - COUNT_TYPE_UNSPECIFIED = 0 - TOTAL_NO_MATCH_COUNT = 1 - TOTAL_TURN_COUNT = 2 - AVERAGE_TURN_COUNT = 3 - - class ConfidenceInterval(proto.Message): - r"""A confidence interval is a range of possible values for the - experiment objective you are trying to measure. - - Attributes: - confidence_level (float): - The confidence level used to construct the - interval, i.e. there is X% chance that the true - value is within this interval. - ratio (float): - The percent change between an experiment - metric's value and the value for its control. - lower_bound (float): - Lower bound of the interval. - upper_bound (float): - Upper bound of the interval. - """ - - confidence_level = proto.Field( - proto.DOUBLE, - number=1, - ) - ratio = proto.Field( - proto.DOUBLE, - number=2, - ) - lower_bound = proto.Field( - proto.DOUBLE, - number=3, - ) - upper_bound = proto.Field( - proto.DOUBLE, - number=4, - ) - - class Metric(proto.Message): - r"""Metric and corresponding confidence intervals. - Attributes: - type_ (google.cloud.dialogflowcx_v3.types.Experiment.Result.MetricType): - Ratio-based metric type. Only one of type or count_type is - specified in each Metric. - count_type (google.cloud.dialogflowcx_v3.types.Experiment.Result.CountType): - Count-based metric type. Only one of type or count_type is - specified in each Metric. - ratio (float): - Ratio value of a metric. - count (float): - Count value of a metric. - confidence_interval (google.cloud.dialogflowcx_v3.types.Experiment.Result.ConfidenceInterval): - The probability that the treatment is better - than all other treatments in the experiment - """ - - type_ = proto.Field( - proto.ENUM, - number=1, - enum='Experiment.Result.MetricType', - ) - count_type = proto.Field( - proto.ENUM, - number=5, - enum='Experiment.Result.CountType', - ) - ratio = proto.Field( - proto.DOUBLE, - number=2, - oneof='value', - ) - count = proto.Field( - proto.DOUBLE, - number=4, - oneof='value', - ) - confidence_interval = proto.Field( - proto.MESSAGE, - number=3, - message='Experiment.Result.ConfidenceInterval', - ) - - class VersionMetrics(proto.Message): - r"""Version variant and associated metrics. - Attributes: - version (str): - The name of the flow - [Version][google.cloud.dialogflow.cx.v3.Version]. Format: - ``projects//locations//agents//flows//versions/``. - metrics (Sequence[google.cloud.dialogflowcx_v3.types.Experiment.Result.Metric]): - The metrics and corresponding confidence - intervals in the inference result. - session_count (int): - Number of sessions that were allocated to - this version. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - metrics = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Experiment.Result.Metric', - ) - session_count = proto.Field( - proto.INT32, - number=3, - ) - - version_metrics = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Experiment.Result.VersionMetrics', - ) - last_update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - state = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - definition = proto.Field( - proto.MESSAGE, - number=5, - message=Definition, - ) - result = proto.Field( - proto.MESSAGE, - number=6, - message=Result, - ) - create_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - start_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - last_update_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - experiment_length = proto.Field( - proto.MESSAGE, - number=11, - message=duration_pb2.Duration, - ) - variants_history = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='VariantsHistory', - ) - - -class VersionVariants(proto.Message): - r"""A list of flow version variants. - Attributes: - variants (Sequence[google.cloud.dialogflowcx_v3.types.VersionVariants.Variant]): - A list of flow version variants. - """ - - class Variant(proto.Message): - r"""A single flow version with specified traffic allocation. - Attributes: - version (str): - The name of the flow version. Format: - ``projects//locations//agents//flows//versions/``. - traffic_allocation (float): - Percentage of the traffic which should be - routed to this version of flow. Traffic - allocation for a single flow must sum up to 1.0. - is_control_group (bool): - Whether the variant is for the control group. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - traffic_allocation = proto.Field( - proto.FLOAT, - number=2, - ) - is_control_group = proto.Field( - proto.BOOL, - number=3, - ) - - variants = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Variant, - ) - - -class VariantsHistory(proto.Message): - r"""The history of variants update. - Attributes: - version_variants (google.cloud.dialogflowcx_v3.types.VersionVariants): - The flow versions as the variants. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Update time of the variants. - """ - - version_variants = proto.Field( - proto.MESSAGE, - number=1, - oneof='variants', - message='VersionVariants', - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class ListExperimentsRequest(proto.Message): - r"""The request message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. - - Attributes: - parent (str): - Required. The - [Environment][google.cloud.dialogflow.cx.v3.Environment] to - list all environments for. Format: - ``projects//locations//agents//environments/``. - page_size (int): - The maximum number of items to return in a - single page. By default 20 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 ListExperimentsResponse(proto.Message): - r"""The response message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3.Experiments.ListExperiments]. - - Attributes: - experiments (Sequence[google.cloud.dialogflowcx_v3.types.Experiment]): - The list of experiments. There will be a maximum number of - items returned based on the page_size field in the request. - The list may in some cases be empty or contain fewer entries - than page_size even if this isn't the last page. - 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 - - experiments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Experiment', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetExperimentRequest(proto.Message): - r"""The request message for - [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3.Experiments.GetExperiment]. - - Attributes: - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment]. - Format: - ``projects//locations//agents//environments//experiments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateExperimentRequest(proto.Message): - r"""The request message for - [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3.Experiments.CreateExperiment]. - - Attributes: - parent (str): - Required. The [Agent][google.cloud.dialogflow.cx.v3.Agent] - to create an - [Environment][google.cloud.dialogflow.cx.v3.Environment] - for. Format: - ``projects//locations//agents//environments/``. - experiment (google.cloud.dialogflowcx_v3.types.Experiment): - Required. The experiment to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - experiment = proto.Field( - proto.MESSAGE, - number=2, - message='Experiment', - ) - - -class UpdateExperimentRequest(proto.Message): - r"""The request message for - [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3.Experiments.UpdateExperiment]. - - Attributes: - experiment (google.cloud.dialogflowcx_v3.types.Experiment): - Required. The experiment to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields - get updated. - """ - - experiment = proto.Field( - proto.MESSAGE, - number=1, - message='Experiment', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteExperimentRequest(proto.Message): - r"""The request message for - [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3.Experiments.DeleteExperiment]. - - Attributes: - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3.Environment] to - delete. Format: - ``projects//locations//agents//environments//experiments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class StartExperimentRequest(proto.Message): - r"""The request message for - [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3.Experiments.StartExperiment]. - - Attributes: - name (str): - Required. Resource name of the experiment to start. Format: - ``projects//locations//agents//environments//experiments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class StopExperimentRequest(proto.Message): - r"""The request message for - [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3.Experiments.StopExperiment]. - - Attributes: - name (str): - Required. Resource name of the experiment to stop. Format: - ``projects//locations//agents//environments//experiments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py deleted file mode 100644 index 766f9cff..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/flow.py +++ /dev/null @@ -1,640 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import validation_message -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'NluSettings', - 'Flow', - 'CreateFlowRequest', - 'DeleteFlowRequest', - 'ListFlowsRequest', - 'ListFlowsResponse', - 'GetFlowRequest', - 'UpdateFlowRequest', - 'TrainFlowRequest', - 'ValidateFlowRequest', - 'GetFlowValidationResultRequest', - 'FlowValidationResult', - 'ImportFlowRequest', - 'ImportFlowResponse', - 'ExportFlowRequest', - 'ExportFlowResponse', - }, -) - - -class NluSettings(proto.Message): - r"""Settings related to NLU. - Attributes: - model_type (google.cloud.dialogflowcx_v3.types.NluSettings.ModelType): - Indicates the type of NLU model. - classification_threshold (float): - 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 no-match event 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. - model_training_mode (google.cloud.dialogflowcx_v3.types.NluSettings.ModelTrainingMode): - Indicates NLU model training mode. - """ - class ModelType(proto.Enum): - r"""NLU model type.""" - MODEL_TYPE_UNSPECIFIED = 0 - MODEL_TYPE_STANDARD = 1 - MODEL_TYPE_ADVANCED = 3 - - class ModelTrainingMode(proto.Enum): - r"""NLU model training mode.""" - MODEL_TRAINING_MODE_UNSPECIFIED = 0 - MODEL_TRAINING_MODE_AUTOMATIC = 1 - MODEL_TRAINING_MODE_MANUAL = 2 - - model_type = proto.Field( - proto.ENUM, - number=1, - enum=ModelType, - ) - classification_threshold = proto.Field( - proto.FLOAT, - number=3, - ) - model_training_mode = proto.Field( - proto.ENUM, - number=4, - enum=ModelTrainingMode, - ) - - -class Flow(proto.Message): - r"""Flows represents the conversation flows when you build your - chatbot agent. - A flow consists of many pages connected by the transition - routes. Conversations always start with the built-in Start Flow - (with an all-0 ID). Transition routes can direct the - conversation session from the current flow (parent flow) to - another flow (sub flow). When the sub flow is finished, - Dialogflow will bring the session back to the parent flow, where - the sub flow is started. - - Usually, when a transition route is followed by a matched - intent, the intent will be "consumed". This means the intent - won't activate more transition routes. However, when the - followed transition route moves the conversation session into a - different flow, the matched intent can be carried over and to be - consumed in the target flow. - - Attributes: - name (str): - The unique identifier of the flow. Format: - ``projects//locations//agents//flows/``. - display_name (str): - Required. The human-readable name of the - flow. - description (str): - The description of the flow. The maximum - length is 500 characters. If exceeded, the - request is rejected. - transition_routes (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRoute]): - A flow's transition routes serve two purposes: - - - They are responsible for matching the user's first - utterances in the flow. - - They are inherited by every page's [transition - routes][Page.transition_routes] and can support use cases - such as the user saying "help" or "can I talk to a - human?", which can be handled in a common way regardless - of the current page. Transition routes defined in the - page have higher priority than those defined in the flow. - - TransitionRoutes are evalauted in the following order: - - - TransitionRoutes with intent specified.. - - TransitionRoutes with only condition specified. - - TransitionRoutes with intent specified are inherited by - pages in the flow. - event_handlers (Sequence[google.cloud.dialogflowcx_v3.types.EventHandler]): - A flow's event handlers serve two purposes: - - - They are responsible for handling events (e.g. no match, - webhook errors) in the flow. - - They are inherited by every page's [event - handlers][Page.event_handlers], which can be used to - handle common events regardless of the current page. - Event handlers defined in the page have higher priority - than those defined in the flow. - - Unlike - [transition_routes][google.cloud.dialogflow.cx.v3.Flow.transition_routes], - these handlers are evaluated on a first-match basis. The - first one that matches the event get executed, with the rest - being ignored. - transition_route_groups (Sequence[str]): - A flow's transition route group serve two purposes: - - - They are responsible for matching the user's first - utterances in the flow. - - They are inherited by every page's [transition route - groups][Page.transition_route_groups]. Transition route - groups defined in the page have higher priority than - those defined in the flow. - - Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. - nlu_settings (google.cloud.dialogflowcx_v3.types.NluSettings): - NLU related settings of the flow. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - transition_routes = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=page.TransitionRoute, - ) - event_handlers = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=page.EventHandler, - ) - transition_route_groups = proto.RepeatedField( - proto.STRING, - number=15, - ) - nlu_settings = proto.Field( - proto.MESSAGE, - number=11, - message='NluSettings', - ) - - -class CreateFlowRequest(proto.Message): - r"""The request message for - [Flows.CreateFlow][google.cloud.dialogflow.cx.v3.Flows.CreateFlow]. - - Attributes: - parent (str): - Required. The agent to create a flow for. Format: - ``projects//locations//agents/``. - flow (google.cloud.dialogflowcx_v3.types.Flow): - Required. The flow to create. - language_code (str): - The language of the following fields in ``flow``: - - - ``Flow.event_handlers.trigger_fulfillment.messages`` - - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Flow.transition_routes.trigger_fulfillment.messages`` - - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - flow = proto.Field( - proto.MESSAGE, - number=2, - message='Flow', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteFlowRequest(proto.Message): - r"""The request message for - [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3.Flows.DeleteFlow]. - - Attributes: - name (str): - Required. The name of the flow to delete. Format: - ``projects//locations//agents//flows/``. - force (bool): - This field has no effect for flows with no incoming - transitions. For flows with incoming transitions: - - - If ``force`` is set to false, an error will be returned - with message indicating the incoming transitions. - - If ``force`` is set to true, Dialogflow will remove the - flow, as well as any transitions to the flow (i.e. - [Target flow][EventHandler.target_flow] in event handlers - or [Target flow][TransitionRoute.target_flow] in - transition routes that point to this flow will be - cleared). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -class ListFlowsRequest(proto.Message): - r"""The request message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. - - Attributes: - parent (str): - Required. The agent containing the flows. Format: - ``projects//locations//agents/``. - 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. - language_code (str): - The language to list flows for. The following fields are - language dependent: - - - ``Flow.event_handlers.trigger_fulfillment.messages`` - - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Flow.transition_routes.trigger_fulfillment.messages`` - - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - - -class ListFlowsResponse(proto.Message): - r"""The response message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3.Flows.ListFlows]. - - Attributes: - flows (Sequence[google.cloud.dialogflowcx_v3.types.Flow]): - The list of flows. 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 - - flows = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Flow', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetFlowRequest(proto.Message): - r"""The response message for - [Flows.GetFlow][google.cloud.dialogflow.cx.v3.Flows.GetFlow]. - - Attributes: - name (str): - Required. The name of the flow to get. Format: - ``projects//locations//agents//flows/``. - language_code (str): - The language to retrieve the flow for. The following fields - are language dependent: - - - ``Flow.event_handlers.trigger_fulfillment.messages`` - - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Flow.transition_routes.trigger_fulfillment.messages`` - - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateFlowRequest(proto.Message): - r"""The request message for - [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3.Flows.UpdateFlow]. - - Attributes: - flow (google.cloud.dialogflowcx_v3.types.Flow): - Required. The flow to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields get updated. If - ``update_mask`` is not specified, an error will be returned. - language_code (str): - The language of the following fields in ``flow``: - - - ``Flow.event_handlers.trigger_fulfillment.messages`` - - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Flow.transition_routes.trigger_fulfillment.messages`` - - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - flow = proto.Field( - proto.MESSAGE, - number=1, - message='Flow', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class TrainFlowRequest(proto.Message): - r"""The request message for - [Flows.TrainFlow][google.cloud.dialogflow.cx.v3.Flows.TrainFlow]. - - Attributes: - name (str): - Required. The flow to train. Format: - ``projects//locations//agents//flows/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ValidateFlowRequest(proto.Message): - r"""The request message for - [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3.Flows.ValidateFlow]. - - Attributes: - name (str): - Required. The flow to validate. Format: - ``projects//locations//agents//flows/``. - language_code (str): - If not specified, the agent's default - language is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class GetFlowValidationResultRequest(proto.Message): - r"""The request message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. - - Attributes: - name (str): - Required. The flow name. Format: - ``projects//locations//agents//flows//validationResult``. - language_code (str): - If not specified, the agent's default - language is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class FlowValidationResult(proto.Message): - r"""The response message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3.Flows.GetFlowValidationResult]. - - Attributes: - name (str): - The unique identifier of the flow validation result. Format: - ``projects//locations//agents//flows//validationResult``. - validation_messages (Sequence[google.cloud.dialogflowcx_v3.types.ValidationMessage]): - Contains all validation messages. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Last time the flow was validated. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - validation_messages = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=validation_message.ValidationMessage, - ) - update_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class ImportFlowRequest(proto.Message): - r"""The request message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. - - Attributes: - parent (str): - Required. The agent to import the flow into. Format: - ``projects//locations//agents/``. - flow_uri (str): - The `Google Cloud - Storage `__ URI to - import flow from. The format of this URI must be - ``gs:///``. - flow_content (bytes): - Uncompressed raw byte content for flow. - import_option (google.cloud.dialogflowcx_v3.types.ImportFlowRequest.ImportOption): - Flow import mode. If not specified, ``KEEP`` is assumed. - """ - class ImportOption(proto.Enum): - r"""Import option.""" - IMPORT_OPTION_UNSPECIFIED = 0 - KEEP = 1 - FALLBACK = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - flow_uri = proto.Field( - proto.STRING, - number=2, - oneof='flow', - ) - flow_content = proto.Field( - proto.BYTES, - number=3, - oneof='flow', - ) - import_option = proto.Field( - proto.ENUM, - number=4, - enum=ImportOption, - ) - - -class ImportFlowResponse(proto.Message): - r"""The response message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. - - Attributes: - flow (str): - The unique identifier of the new flow. Format: - ``projects//locations//agents//flows/``. - """ - - flow = proto.Field( - proto.STRING, - number=1, - ) - - -class ExportFlowRequest(proto.Message): - r"""The request message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. - - Attributes: - name (str): - Required. The name of the flow to export. Format: - ``projects//locations//agents//flows/``. - flow_uri (str): - Optional. The `Google Cloud - Storage `__ URI to - export the flow to. The format of this URI must be - ``gs:///``. If left unspecified, - the serialized flow is returned inline. - include_referenced_flows (bool): - Optional. Whether to export flows referenced - by the specified flow. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - flow_uri = proto.Field( - proto.STRING, - number=2, - ) - include_referenced_flows = proto.Field( - proto.BOOL, - number=4, - ) - - -class ExportFlowResponse(proto.Message): - r"""The response message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. - - Attributes: - flow_uri (str): - The URI to a file containing the exported flow. This field - is populated only if ``flow_uri`` is specified in - [ExportFlowRequest][google.cloud.dialogflow.cx.v3.ExportFlowRequest]. - flow_content (bytes): - Uncompressed raw byte content for flow. - """ - - flow_uri = proto.Field( - proto.STRING, - number=1, - oneof='flow', - ) - flow_content = proto.Field( - proto.BYTES, - number=2, - oneof='flow', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py deleted file mode 100644 index 93f3b79c..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/fulfillment.py +++ /dev/null @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import response_message -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'Fulfillment', - }, -) - - -class Fulfillment(proto.Message): - r"""A fulfillment can do one or more of the following actions at the - same time: - - - Generate rich message responses. - - Set parameter values. - - Call the webhook. - - Fulfillments can be called at various stages in the - [Page][google.cloud.dialogflow.cx.v3.Page] or - [Form][google.cloud.dialogflow.cx.v3.Form] lifecycle. For example, - when a - [DetectIntentRequest][google.cloud.dialogflow.cx.v3.DetectIntentRequest] - drives a session to enter a new page, the page's entry fulfillment - can add a static response to the - [QueryResult][google.cloud.dialogflow.cx.v3.QueryResult] in the - returning - [DetectIntentResponse][google.cloud.dialogflow.cx.v3.DetectIntentResponse], - call the webhook (for example, to load user data from a database), - or both. - - Attributes: - messages (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage]): - The list of rich message responses to present - to the user. - webhook (str): - The webhook to call. Format: - ``projects//locations//agents//webhooks/``. - tag (str): - The tag used by the webhook to identify which fulfillment is - being called. This field is required if ``webhook`` is - specified. - set_parameter_actions (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.SetParameterAction]): - Set parameter values before executing the - webhook. - conditional_cases (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases]): - Conditional cases for this fulfillment. - """ - - class SetParameterAction(proto.Message): - r"""Setting a parameter value. - Attributes: - parameter (str): - Display name of the parameter. - value (google.protobuf.struct_pb2.Value): - The new value of the parameter. A null value - clears the parameter. - """ - - parameter = proto.Field( - proto.STRING, - number=1, - ) - value = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - class ConditionalCases(proto.Message): - r"""A list of cascading if-else conditions. Cases are mutually - exclusive. The first one with a matching condition is selected, - all the rest ignored. - - Attributes: - cases (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases.Case]): - A list of cascading if-else conditions. - """ - - class Case(proto.Message): - r"""Each case has a Boolean condition. When it is evaluated to be - True, the corresponding messages will be selected and evaluated - recursively. - - Attributes: - condition (str): - The condition to activate and select this case. Empty means - the condition is always true. The condition is evaluated - against [form parameters][Form.parameters] or [session - parameters][SessionInfo.parameters]. - - See the `conditions - reference `__. - case_content (Sequence[google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases.Case.CaseContent]): - A list of case content. - """ - - class CaseContent(proto.Message): - r"""The list of messages or conditional cases to activate for - this case. - - Attributes: - message (google.cloud.dialogflowcx_v3.types.ResponseMessage): - Returned message. - additional_cases (google.cloud.dialogflowcx_v3.types.Fulfillment.ConditionalCases): - Additional cases to be evaluated. - """ - - message = proto.Field( - proto.MESSAGE, - number=1, - oneof='cases_or_message', - message=response_message.ResponseMessage, - ) - additional_cases = proto.Field( - proto.MESSAGE, - number=2, - oneof='cases_or_message', - message='Fulfillment.ConditionalCases', - ) - - condition = proto.Field( - proto.STRING, - number=1, - ) - case_content = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Fulfillment.ConditionalCases.Case.CaseContent', - ) - - cases = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Fulfillment.ConditionalCases.Case', - ) - - messages = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=response_message.ResponseMessage, - ) - webhook = proto.Field( - proto.STRING, - number=2, - ) - tag = proto.Field( - proto.STRING, - number=3, - ) - set_parameter_actions = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=SetParameterAction, - ) - conditional_cases = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=ConditionalCases, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py deleted file mode 100644 index b0b25b6a..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/intent.py +++ /dev/null @@ -1,474 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cx.v3', - manifest={ - 'IntentView', - 'Intent', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'GetIntentRequest', - 'CreateIntentRequest', - 'UpdateIntentRequest', - 'DeleteIntentRequest', - }, -) - - -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. - """ - INTENT_VIEW_UNSPECIFIED = 0 - INTENT_VIEW_PARTIAL = 1 - INTENT_VIEW_FULL = 2 - - -class Intent(proto.Message): - r"""An intent represents a user's intent to interact with a - conversational agent. - You can provide information for the Dialogflow API to use to - match user input to an intent by adding training phrases (i.e., - examples of user input) to your intent. - - Attributes: - name (str): - The unique identifier of the intent. Required for the - [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent] - method. - [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent] - populates the name automatically. Format: - ``projects//locations//agents//intents/``. - display_name (str): - Required. The human-readable name of the - intent, unique within the agent. - training_phrases (Sequence[google.cloud.dialogflowcx_v3.types.Intent.TrainingPhrase]): - The collection of training phrases the agent - is trained on to identify the intent. - parameters (Sequence[google.cloud.dialogflowcx_v3.types.Intent.Parameter]): - The collection of parameters associated with - the intent. - priority (int): - 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): - Indicates whether this is a fallback intent. - Currently only default fallback intent is - allowed in the agent, which is added upon agent - creation. - Adding training phrases to fallback intent is - useful in the case of requests that are - mistakenly matched, since training phrases - assigned to fallback intents act as negative - examples that triggers no-match event. - labels (Sequence[google.cloud.dialogflowcx_v3.types.Intent.LabelsEntry]): - The key/value metadata to label an intent. Labels can - contain lowercase letters, digits and the symbols '-' and - '_'. International characters are allowed, including letters - from unicase alphabets. Keys must start with a letter. Keys - and values can be no longer than 63 characters and no more - than 128 bytes. - - Prefix "sys." is reserved for Dialogflow defined labels. - Currently allowed Dialogflow defined labels include: - - - sys.head - - sys.contextual The above labels do not require value. - "sys.head" means the intent is a head intent. - "sys.contextual" means the intent is a contextual intent. - description (str): - Human readable description for better - understanding an intent like its scope, content, - result etc. Maximum character limit: 140 - characters. - """ - - class TrainingPhrase(proto.Message): - r"""Represents an example that the agent is trained on to - identify the intent. - - Attributes: - id (str): - Output only. The unique identifier of the - training phrase. - parts (Sequence[google.cloud.dialogflowcx_v3.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.cx.v3.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 ``parameter_id`` field is set. - repeat_count (int): - Indicates how many times this example was - added to the intent. - """ - - class Part(proto.Message): - r"""Represents a part of a training phrase. - Attributes: - text (str): - Required. The text for this part. - parameter_id (str): - The - [parameter][google.cloud.dialogflow.cx.v3.Intent.Parameter] - used to annotate this part of the training phrase. This - field is required for annotated parts of the training - phrase. - """ - - text = proto.Field( - proto.STRING, - number=1, - ) - parameter_id = proto.Field( - proto.STRING, - number=2, - ) - - id = proto.Field( - proto.STRING, - number=1, - ) - parts = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.TrainingPhrase.Part', - ) - repeat_count = proto.Field( - proto.INT32, - number=3, - ) - - class Parameter(proto.Message): - r"""Represents an intent parameter. - Attributes: - id (str): - Required. The unique identifier of the parameter. This field - is used by [training - phrases][google.cloud.dialogflow.cx.v3.Intent.TrainingPhrase] - to annotate their - [parts][google.cloud.dialogflow.cx.v3.Intent.TrainingPhrase.Part]. - entity_type (str): - Required. The entity type of the parameter. Format: - ``projects/-/locations/-/agents/-/entityTypes/`` - for system entity types (for example, - ``projects/-/locations/-/agents/-/entityTypes/sys.date``), - or - ``projects//locations//agents//entityTypes/`` - for developer entity types. - is_list (bool): - Indicates whether the parameter represents a - list of values. - redact (bool): - Indicates whether the parameter content should be redacted - in log. If redaction is enabled, the parameter content will - be replaced by parameter name during logging. Note: the - parameter content is subject to redaction if either - parameter level redaction or [entity type level - redaction][google.cloud.dialogflow.cx.v3.EntityType.redact] - is enabled. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - entity_type = proto.Field( - proto.STRING, - number=2, - ) - is_list = proto.Field( - proto.BOOL, - number=3, - ) - redact = proto.Field( - proto.BOOL, - number=4, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - training_phrases = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=TrainingPhrase, - ) - parameters = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Parameter, - ) - priority = proto.Field( - proto.INT32, - number=5, - ) - is_fallback = proto.Field( - proto.BOOL, - number=6, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - description = proto.Field( - proto.STRING, - number=8, - ) - - -class ListIntentsRequest(proto.Message): - r"""The request message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. - - Attributes: - parent (str): - Required. The agent to list all intents for. Format: - ``projects//locations//agents/``. - language_code (str): - The language to list intents for. The following fields are - language dependent: - - - ``Intent.training_phrases.parts.text`` - - 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. - intent_view (google.cloud.dialogflowcx_v3.types.IntentView): - The resource view to apply to the returned - intent. - 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, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - intent_view = proto.Field( - proto.ENUM, - number=5, - enum='IntentView', - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListIntentsResponse(proto.Message): - r"""The response message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3.Intents.ListIntents]. - - Attributes: - intents (Sequence[google.cloud.dialogflowcx_v3.types.Intent]): - The list of 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.cx.v3.Intents.GetIntent]. - - Attributes: - name (str): - Required. The name of the intent. Format: - ``projects//locations//agents//intents/``. - language_code (str): - The language to retrieve the intent for. The following - fields are language dependent: - - - ``Intent.training_phrases.parts.text`` - - 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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateIntentRequest(proto.Message): - r"""The request message for - [Intents.CreateIntent][google.cloud.dialogflow.cx.v3.Intents.CreateIntent]. - - Attributes: - parent (str): - Required. The agent to create an intent for. Format: - ``projects//locations//agents/``. - intent (google.cloud.dialogflowcx_v3.types.Intent): - Required. The intent to create. - language_code (str): - The language of the following fields in ``intent``: - - - ``Intent.training_phrases.parts.text`` - - 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, - ) - intent = proto.Field( - proto.MESSAGE, - number=2, - message='Intent', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateIntentRequest(proto.Message): - r"""The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3.Intents.UpdateIntent]. - - Attributes: - intent (google.cloud.dialogflowcx_v3.types.Intent): - Required. The intent to update. - language_code (str): - The language of the following fields in ``intent``: - - - ``Intent.training_phrases.parts.text`` - - 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. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The mask to control which fields get updated. - If the mask is not present, all fields will be - updated. - """ - - 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, - ) - - -class DeleteIntentRequest(proto.Message): - r"""The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3.Intents.DeleteIntent]. - - Attributes: - name (str): - Required. The name of the intent to delete. Format: - ``projects//locations//agents//intents/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py deleted file mode 100644 index ee4be110..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/page.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import fulfillment -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'Page', - 'Form', - 'EventHandler', - 'TransitionRoute', - 'ListPagesRequest', - 'ListPagesResponse', - 'GetPageRequest', - 'CreatePageRequest', - 'UpdatePageRequest', - 'DeletePageRequest', - }, -) - - -class Page(proto.Message): - r"""A Dialogflow CX conversation (session) can be described and - visualized as a state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your combined pages can - handle a complete conversation on the topics the flow is designed - for. At any given moment, exactly one page is the current page, the - current page is considered active, and the flow associated with that - page is considered active. Every flow has a special start page. When - a flow initially becomes active, the start page page becomes the - current page. For each conversational turn, the current page will - either stay the same or transition to another page. - - You configure each page to collect information from the end-user - that is relevant for the conversational state represented by the - page. - - For more information, see the `Page - guide `__. - - Attributes: - name (str): - The unique identifier of the page. Required for the - [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage] - method. - [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage] - populates the name automatically. Format: - ``projects//locations//agents//flows//pages/``. - display_name (str): - Required. The human-readable name of the - page, unique within the agent. - entry_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): - The fulfillment to call when the session is - entering the page. - form (google.cloud.dialogflowcx_v3.types.Form): - The form associated with the page, used for - collecting parameters relevant to the page. - transition_route_groups (Sequence[str]): - Ordered list of - [``TransitionRouteGroups``][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - associated with the page. Transition route groups must be - unique within a page. - - - If multiple transition routes within a page scope refer - to the same intent, then the precedence order is: page's - transition route -> page's transition route group -> - flow's transition routes. - - - If multiple transition route groups within a page contain - the same intent, then the first group in the ordered list - takes precedence. - - Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. - transition_routes (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRoute]): - A list of transitions for the transition rules of this page. - They route the conversation to another page in the same - flow, or another flow. - - When we are in a certain page, the TransitionRoutes are - evalauted in the following order: - - - TransitionRoutes defined in the page with intent - specified. - - TransitionRoutes defined in the [transition route - groups][google.cloud.dialogflow.cx.v3.Page.transition_route_groups] - with intent specified. - - TransitionRoutes defined in flow with intent specified. - - TransitionRoutes defined in the [transition route - groups][google.cloud.dialogflow.cx.v3.Flow.transition_route_groups] - with intent specified. - - TransitionRoutes defined in the page with only condition - specified. - - TransitionRoutes defined in the [transition route - groups][google.cloud.dialogflow.cx.v3.Page.transition_route_groups] - with only condition specified. - event_handlers (Sequence[google.cloud.dialogflowcx_v3.types.EventHandler]): - Handlers associated with the page to handle - events such as webhook errors, no match or no - input. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - entry_fulfillment = proto.Field( - proto.MESSAGE, - number=7, - message=fulfillment.Fulfillment, - ) - form = proto.Field( - proto.MESSAGE, - number=4, - message='Form', - ) - transition_route_groups = proto.RepeatedField( - proto.STRING, - number=11, - ) - transition_routes = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='TransitionRoute', - ) - event_handlers = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='EventHandler', - ) - - -class Form(proto.Message): - r"""A form is a data model that groups related parameters that can be - collected from the user. The process in which the agent prompts the - user and collects parameter values from the user is called form - filling. A form can be added to a - [page][google.cloud.dialogflow.cx.v3.Page]. When form filling is - done, the filled parameters will be written to the - [session][google.cloud.dialogflow.cx.v3.SessionInfo.parameters]. - - Attributes: - parameters (Sequence[google.cloud.dialogflowcx_v3.types.Form.Parameter]): - Parameters to collect from the user. - """ - - class Parameter(proto.Message): - r"""Represents a form parameter. - Attributes: - display_name (str): - Required. The human-readable name of the - parameter, unique within the form. - required (bool): - Indicates whether the parameter is required. - Optional parameters will not trigger prompts; - however, they are filled if the user specifies - them. Required parameters must be filled before - form filling concludes. - entity_type (str): - Required. The entity type of the parameter. Format: - ``projects/-/locations/-/agents/-/entityTypes/`` - for system entity types (for example, - ``projects/-/locations/-/agents/-/entityTypes/sys.date``), - or - ``projects//locations//agents//entityTypes/`` - for developer entity types. - is_list (bool): - Indicates whether the parameter represents a - list of values. - fill_behavior (google.cloud.dialogflowcx_v3.types.Form.Parameter.FillBehavior): - Required. Defines fill behavior for the - parameter. - default_value (google.protobuf.struct_pb2.Value): - The default value of an optional parameter. - If the parameter is required, the default value - will be ignored. - redact (bool): - Indicates whether the parameter content should be redacted - in log. If redaction is enabled, the parameter content will - be replaced by parameter name during logging. Note: the - parameter content is subject to redaction if either - parameter level redaction or [entity type level - redaction][google.cloud.dialogflow.cx.v3.EntityType.redact] - is enabled. - """ - - class FillBehavior(proto.Message): - r"""Configuration for how the filling of a parameter should be - handled. - - Attributes: - initial_prompt_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): - Required. The fulfillment to provide the - initial prompt that the agent can present to the - user in order to fill the parameter. - reprompt_event_handlers (Sequence[google.cloud.dialogflowcx_v3.types.EventHandler]): - The handlers for parameter-level events, used to provide - reprompt for the parameter or transition to a different - page/flow. The supported events are: - - - ``sys.no-match-``, where N can be from 1 to 6 - - ``sys.no-match-default`` - - ``sys.no-input-``, where N can be from 1 to 6 - - ``sys.no-input-default`` - - ``sys.invalid-parameter`` - - ``initial_prompt_fulfillment`` provides the first prompt for - the parameter. - - If the user's response does not fill the parameter, a - no-match/no-input event will be triggered, and the - fulfillment associated with the - ``sys.no-match-1``/``sys.no-input-1`` handler (if defined) - will be called to provide a prompt. The - ``sys.no-match-2``/``sys.no-input-2`` handler (if defined) - will respond to the next no-match/no-input event, and so on. - - A ``sys.no-match-default`` or ``sys.no-input-default`` - handler will be used to handle all following - no-match/no-input events after all numbered - no-match/no-input handlers for the parameter are consumed. - - A ``sys.invalid-parameter`` handler can be defined to handle - the case where the parameter values have been - ``invalidated`` by webhook. For example, if the user's - response fill the parameter, however the parameter was - invalidated by webhook, the fulfillment associated with the - ``sys.invalid-parameter`` handler (if defined) will be - called to provide a prompt. - - If the event handler for the corresponding event can't be - found on the parameter, ``initial_prompt_fulfillment`` will - be re-prompted. - """ - - initial_prompt_fulfillment = proto.Field( - proto.MESSAGE, - number=3, - message=fulfillment.Fulfillment, - ) - reprompt_event_handlers = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='EventHandler', - ) - - display_name = proto.Field( - proto.STRING, - number=1, - ) - required = proto.Field( - proto.BOOL, - number=2, - ) - entity_type = proto.Field( - proto.STRING, - number=3, - ) - is_list = proto.Field( - proto.BOOL, - number=4, - ) - fill_behavior = proto.Field( - proto.MESSAGE, - number=7, - message='Form.Parameter.FillBehavior', - ) - default_value = proto.Field( - proto.MESSAGE, - number=9, - message=struct_pb2.Value, - ) - redact = proto.Field( - proto.BOOL, - number=11, - ) - - parameters = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Parameter, - ) - - -class EventHandler(proto.Message): - r"""An event handler specifies an - [event][google.cloud.dialogflow.cx.v3.EventHandler.event] that can - be handled during a session. When the specified event happens, the - following actions are taken in order: - - - If there is a - [``trigger_fulfillment``][google.cloud.dialogflow.cx.v3.EventHandler.trigger_fulfillment] - associated with the event, it will be called. - - If there is a - [``target_page``][google.cloud.dialogflow.cx.v3.EventHandler.target_page] - associated with the event, the session will transition into the - specified page. - - If there is a - [``target_flow``][google.cloud.dialogflow.cx.v3.EventHandler.target_flow] - associated with the event, the session will transition into the - specified flow. - - Attributes: - name (str): - Output only. The unique identifier of this - event handler. - event (str): - Required. The name of the event to handle. - trigger_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): - The fulfillment to call when the event - occurs. Handling webhook errors with a - fulfillment enabled with webhook could cause - infinite loop. It is invalid to specify such - fulfillment for a handler handling webhooks. - target_page (str): - The target page to transition to. Format: - ``projects//locations//agents//flows//pages/``. - target_flow (str): - The target flow to transition to. Format: - ``projects//locations//agents//flows/``. - """ - - name = proto.Field( - proto.STRING, - number=6, - ) - event = proto.Field( - proto.STRING, - number=4, - ) - trigger_fulfillment = proto.Field( - proto.MESSAGE, - number=5, - message=fulfillment.Fulfillment, - ) - target_page = proto.Field( - proto.STRING, - number=2, - oneof='target', - ) - target_flow = proto.Field( - proto.STRING, - number=3, - oneof='target', - ) - - -class TransitionRoute(proto.Message): - r"""A transition route specifies a - [intent][google.cloud.dialogflow.cx.v3.Intent] that can be matched - and/or a data condition that can be evaluated during a session. When - a specified transition is matched, the following actions are taken - in order: - - - If there is a - [``trigger_fulfillment``][google.cloud.dialogflow.cx.v3.TransitionRoute.trigger_fulfillment] - associated with the transition, it will be called. - - If there is a - [``target_page``][google.cloud.dialogflow.cx.v3.TransitionRoute.target_page] - associated with the transition, the session will transition into - the specified page. - - If there is a - [``target_flow``][google.cloud.dialogflow.cx.v3.TransitionRoute.target_flow] - associated with the transition, the session will transition into - the specified flow. - - Attributes: - name (str): - Output only. The unique identifier of this - transition route. - intent (str): - The unique identifier of an - [Intent][google.cloud.dialogflow.cx.v3.Intent]. Format: - ``projects//locations//agents//intents/``. - Indicates that the transition can only happen when the given - intent is matched. At least one of ``intent`` or - ``condition`` must be specified. When both ``intent`` and - ``condition`` are specified, the transition can only happen - when both are fulfilled. - condition (str): - The condition to evaluate against [form - parameters][google.cloud.dialogflow.cx.v3.Form.parameters] - or [session - parameters][google.cloud.dialogflow.cx.v3.SessionInfo.parameters]. - - See the `conditions - reference `__. - At least one of ``intent`` or ``condition`` must be - specified. When both ``intent`` and ``condition`` are - specified, the transition can only happen when both are - fulfilled. - trigger_fulfillment (google.cloud.dialogflowcx_v3.types.Fulfillment): - The fulfillment to call when the condition is satisfied. At - least one of ``trigger_fulfillment`` and ``target`` must be - specified. When both are defined, ``trigger_fulfillment`` is - executed first. - target_page (str): - The target page to transition to. Format: - ``projects//locations//agents//flows//pages/``. - target_flow (str): - The target flow to transition to. Format: - ``projects//locations//agents//flows/``. - """ - - name = proto.Field( - proto.STRING, - number=6, - ) - intent = proto.Field( - proto.STRING, - number=1, - ) - condition = proto.Field( - proto.STRING, - number=2, - ) - trigger_fulfillment = proto.Field( - proto.MESSAGE, - number=3, - message=fulfillment.Fulfillment, - ) - target_page = proto.Field( - proto.STRING, - number=4, - oneof='target', - ) - target_flow = proto.Field( - proto.STRING, - number=5, - oneof='target', - ) - - -class ListPagesRequest(proto.Message): - r"""The request message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. - - Attributes: - parent (str): - Required. The flow to list all pages for. Format: - ``projects//locations//agents//flows/``. - language_code (str): - The language to list pages for. The following fields are - language dependent: - - - ``Page.entry_fulfillment.messages`` - - ``Page.entry_fulfillment.conditional_cases`` - - ``Page.event_handlers.trigger_fulfillment.messages`` - - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` - - - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` - - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - 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, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListPagesResponse(proto.Message): - r"""The response message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3.Pages.ListPages]. - - Attributes: - pages (Sequence[google.cloud.dialogflowcx_v3.types.Page]): - The list of pages. 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 - - pages = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Page', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetPageRequest(proto.Message): - r"""The request message for - [Pages.GetPage][google.cloud.dialogflow.cx.v3.Pages.GetPage]. - - Attributes: - name (str): - Required. The name of the page. Format: - ``projects//locations//agents//flows//pages/``. - language_code (str): - The language to retrieve the page for. The following fields - are language dependent: - - - ``Page.entry_fulfillment.messages`` - - ``Page.entry_fulfillment.conditional_cases`` - - ``Page.event_handlers.trigger_fulfillment.messages`` - - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` - - - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` - - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class CreatePageRequest(proto.Message): - r"""The request message for - [Pages.CreatePage][google.cloud.dialogflow.cx.v3.Pages.CreatePage]. - - Attributes: - parent (str): - Required. The flow to create a page for. Format: - ``projects//locations//agents//flows/``. - page (google.cloud.dialogflowcx_v3.types.Page): - Required. The page to create. - language_code (str): - The language of the following fields in ``page``: - - - ``Page.entry_fulfillment.messages`` - - ``Page.entry_fulfillment.conditional_cases`` - - ``Page.event_handlers.trigger_fulfillment.messages`` - - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` - - - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` - - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page = proto.Field( - proto.MESSAGE, - number=2, - message='Page', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdatePageRequest(proto.Message): - r"""The request message for - [Pages.UpdatePage][google.cloud.dialogflow.cx.v3.Pages.UpdatePage]. - - Attributes: - page (google.cloud.dialogflowcx_v3.types.Page): - Required. The page to update. - language_code (str): - The language of the following fields in ``page``: - - - ``Page.entry_fulfillment.messages`` - - ``Page.entry_fulfillment.conditional_cases`` - - ``Page.event_handlers.trigger_fulfillment.messages`` - - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` - - - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` - - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The mask to control which fields get updated. - If the mask is not present, all fields will be - updated. - """ - - page = proto.Field( - proto.MESSAGE, - number=1, - message='Page', - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class DeletePageRequest(proto.Message): - r"""The request message for - [Pages.DeletePage][google.cloud.dialogflow.cx.v3.Pages.DeletePage]. - - Attributes: - name (str): - Required. The name of the page to delete. Format: - ``projects//locations//agents//Flows//pages/``. - force (bool): - This field has no effect for pages with no incoming - transitions. For pages with incoming transitions: - - - If ``force`` is set to false, an error will be returned - with message indicating the incoming transitions. - - If ``force`` is set to true, Dialogflow will remove the - page, as well as any transitions to the page (i.e. - [Target page][EventHandler.target_page] in event handlers - or [Target page][TransitionRoute.target_page] in - transition routes that point to this page will be - cleared). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py deleted file mode 100644 index b6972d26..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/response_message.py +++ /dev/null @@ -1,340 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'ResponseMessage', - }, -) - - -class ResponseMessage(proto.Message): - r"""Represents a response message that can be returned by a - conversational agent. - - Response messages are also used for output audio synthesis. The - approach is as follows: - - - If at least one OutputAudioText response is present, then all - OutputAudioText responses are linearly concatenated, and the - result is used for output audio synthesis. - - If the OutputAudioText responses are a mixture of text and SSML, - then the concatenated result is treated as SSML; otherwise, the - result is treated as either text or SSML as appropriate. The - agent designer should ideally use either text or SSML - consistently throughout the bot design. - - Otherwise, all Text responses are linearly concatenated, and the - result is used for output audio synthesis. - - This approach allows for more sophisticated user experience - scenarios, where the text displayed to the user may differ from what - is heard. - - Attributes: - text (google.cloud.dialogflowcx_v3.types.ResponseMessage.Text): - Returns a text response. - payload (google.protobuf.struct_pb2.Struct): - Returns a response containing a custom, - platform-specific payload. - conversation_success (google.cloud.dialogflowcx_v3.types.ResponseMessage.ConversationSuccess): - Indicates that the conversation succeeded. - output_audio_text (google.cloud.dialogflowcx_v3.types.ResponseMessage.OutputAudioText): - A text or ssml response that is - preferentially used for TTS output audio - synthesis, as described in the comment on the - ResponseMessage message. - live_agent_handoff (google.cloud.dialogflowcx_v3.types.ResponseMessage.LiveAgentHandoff): - Hands off conversation to a human agent. - end_interaction (google.cloud.dialogflowcx_v3.types.ResponseMessage.EndInteraction): - Output only. A signal that indicates the interaction with - the Dialogflow agent has ended. This message is generated by - Dialogflow only when the conversation reaches - ``END_SESSION`` page. It is not supposed to be defined by - the user. - - It's guaranteed that there is at most one such message in - each response. - play_audio (google.cloud.dialogflowcx_v3.types.ResponseMessage.PlayAudio): - Signal that the client should play an audio clip hosted at a - client-specific URI. Dialogflow uses this to construct - [mixed_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.mixed_audio]. - However, Dialogflow itself does not try to read or process - the URI in any way. - mixed_audio (google.cloud.dialogflowcx_v3.types.ResponseMessage.MixedAudio): - Output only. An audio response message composed of both the - synthesized Dialogflow agent responses and responses defined - via - [play_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.play_audio]. - This message is generated by Dialogflow only and not - supposed to be defined by the user. - """ - - class Text(proto.Message): - r"""The text response message. - Attributes: - text (Sequence[str]): - Required. A collection of text responses. - allow_playback_interruption (bool): - Output only. Whether the playback of this - message can be interrupted by the end user's - speech and the client can then starts the next - Dialogflow request. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - allow_playback_interruption = proto.Field( - proto.BOOL, - number=2, - ) - - class LiveAgentHandoff(proto.Message): - r"""Indicates that the conversation should be handed off to a live - 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][google.cloud.dialogflow.cx.v3.Page.entry_fulfillment] - of a [Page][google.cloud.dialogflow.cx.v3.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 ConversationSuccess(proto.Message): - r"""Indicates that the conversation succeeded, i.e., the bot handled the - issue that the customer talked to it about. - - Dialogflow only uses this to determine which conversations should be - counted as successful and doesn't process the metadata in this - message in any way. Note that Dialogflow also considers - conversations that get to the conversation end page as successful - even if they don't return - [ConversationSuccess][google.cloud.dialogflow.cx.v3.ResponseMessage.ConversationSuccess]. - - You may set this, for example: - - - In the - [entry_fulfillment][google.cloud.dialogflow.cx.v3.Page.entry_fulfillment] - of a [Page][google.cloud.dialogflow.cx.v3.Page] if entering the - page indicates that the conversation succeeded. - - In a webhook response when you determine that you handled the - customer issue. - - Attributes: - metadata (google.protobuf.struct_pb2.Struct): - Custom metadata. Dialogflow doesn't impose - any structure on this. - """ - - metadata = proto.Field( - proto.MESSAGE, - number=1, - message=struct_pb2.Struct, - ) - - class OutputAudioText(proto.Message): - r"""A text or ssml response that is preferentially used for TTS - output audio synthesis, as described in the comment on the - ResponseMessage message. - - Attributes: - text (str): - The raw text to be synthesized. - ssml (str): - The SSML text to be synthesized. For more information, see - `SSML `__. - allow_playback_interruption (bool): - Output only. Whether the playback of this - message can be interrupted by the end user's - speech and the client can then starts the next - Dialogflow request. - """ - - text = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - ssml = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - allow_playback_interruption = proto.Field( - proto.BOOL, - number=3, - ) - - class EndInteraction(proto.Message): - r"""Indicates that interaction with the Dialogflow agent has - ended. This message is generated by Dialogflow only and not - supposed to be defined by the user. - """ - - class PlayAudio(proto.Message): - r"""Specifies an audio clip to be played by the client as part of - the response. - - Attributes: - audio_uri (str): - Required. URI of the audio clip. Dialogflow - does not impose any validation on this value. It - is specific to the client that reads it. - allow_playback_interruption (bool): - Output only. Whether the playback of this - message can be interrupted by the end user's - speech and the client can then starts the next - Dialogflow request. - """ - - audio_uri = proto.Field( - proto.STRING, - number=1, - ) - allow_playback_interruption = proto.Field( - proto.BOOL, - number=2, - ) - - class MixedAudio(proto.Message): - r"""Represents an audio message that is composed of both segments - synthesized from the Dialogflow agent prompts and ones hosted - externally at the specified URIs. The external URIs are specified - via - [play_audio][google.cloud.dialogflow.cx.v3.ResponseMessage.play_audio]. - This message is generated by Dialogflow only and not supposed to be - defined by the user. - - Attributes: - segments (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage.MixedAudio.Segment]): - Segments this audio response is composed of. - """ - - class Segment(proto.Message): - r"""Represents one segment of audio. - Attributes: - audio (bytes): - Raw audio synthesized from the Dialogflow - agent's response using the output config - specified in the request. - uri (str): - Client-specific URI that points to an audio - clip accessible to the client. Dialogflow does - not impose any validation on it. - allow_playback_interruption (bool): - Output only. Whether the playback of this - segment can be interrupted by the end user's - speech and the client should then start the next - Dialogflow request. - """ - - audio = proto.Field( - proto.BYTES, - number=1, - oneof='content', - ) - uri = proto.Field( - proto.STRING, - number=2, - oneof='content', - ) - allow_playback_interruption = proto.Field( - proto.BOOL, - number=3, - ) - - segments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ResponseMessage.MixedAudio.Segment', - ) - - text = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message=Text, - ) - payload = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message=struct_pb2.Struct, - ) - conversation_success = proto.Field( - proto.MESSAGE, - number=9, - oneof='message', - message=ConversationSuccess, - ) - output_audio_text = proto.Field( - proto.MESSAGE, - number=8, - oneof='message', - message=OutputAudioText, - ) - live_agent_handoff = proto.Field( - proto.MESSAGE, - number=10, - oneof='message', - message=LiveAgentHandoff, - ) - end_interaction = proto.Field( - proto.MESSAGE, - number=11, - oneof='message', - message=EndInteraction, - ) - play_audio = proto.Field( - proto.MESSAGE, - number=12, - oneof='message', - message=PlayAudio, - ) - mixed_audio = proto.Field( - proto.MESSAGE, - number=13, - oneof='message', - message=MixedAudio, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py deleted file mode 100644 index 3ff3778e..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/security_settings.py +++ /dev/null @@ -1,267 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cx.v3', - manifest={ - 'GetSecuritySettingsRequest', - 'UpdateSecuritySettingsRequest', - 'ListSecuritySettingsRequest', - 'ListSecuritySettingsResponse', - 'CreateSecuritySettingsRequest', - 'DeleteSecuritySettingsRequest', - 'SecuritySettings', - }, -) - - -class GetSecuritySettingsRequest(proto.Message): - r"""The request message for - [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.GetSecuritySettings]. - - Attributes: - name (str): - Required. Resource name of the settings. Format: - ``projects//locations//securitySettings/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateSecuritySettingsRequest(proto.Message): - r"""The request message for - [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. - - Attributes: - security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): - Required. [SecuritySettings] object that contains values for - each of the fields 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. - """ - - security_settings = proto.Field( - proto.MESSAGE, - number=1, - message='SecuritySettings', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListSecuritySettingsRequest(proto.Message): - r"""The request message for [SecuritySettings.ListSecuritySettings][]. - Attributes: - parent (str): - Required. The location to list all security settings for. - Format: ``projects//locations/``. - page_size (int): - The maximum number of items to return in a - single page. By default 20 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 ListSecuritySettingsResponse(proto.Message): - r"""The response message for [SecuritySettings.ListSecuritySettings][]. - Attributes: - security_settings (Sequence[google.cloud.dialogflowcx_v3.types.SecuritySettings]): - The list of security settings. - 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 - - security_settings = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SecuritySettings', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateSecuritySettingsRequest(proto.Message): - r"""The request message for [SecuritySettings.CreateSecuritySettings][]. - Attributes: - parent (str): - Required. The location to create an - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] - for. Format: - ``projects//locations/``. - security_settings (google.cloud.dialogflowcx_v3.types.SecuritySettings): - Required. The security settings to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - security_settings = proto.Field( - proto.MESSAGE, - number=2, - message='SecuritySettings', - ) - - -class DeleteSecuritySettingsRequest(proto.Message): - r"""The request message for [SecuritySettings.DeleteSecuritySettings][]. - Attributes: - name (str): - Required. The name of the - [SecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettings] - to delete. Format: - ``projects//locations//securitySettings/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class SecuritySettings(proto.Message): - r"""Represents the settings related to security issues, such as - data redaction and data retention. It may take hours for updates - on the settings to propagate to all the related components and - take effect. - - Attributes: - name (str): - Required. Resource name of the settings. Format: - ``projects//locations//securitySettings/``. - display_name (str): - Required. The human-readable name of the - security settings, unique within the location. - redaction_strategy (google.cloud.dialogflowcx_v3.types.SecuritySettings.RedactionStrategy): - Strategy that defines how we do redaction. - redaction_scope (google.cloud.dialogflowcx_v3.types.SecuritySettings.RedactionScope): - Defines the data for which Dialogflow applies - redaction. Dialogflow does not redact data that - it does not have access to – for example, Cloud - logging. - inspect_template (str): - DLP inspect template name. Use this template to define - inspect base settings. - - If empty, we use the default DLP inspect config. - - The template name will have one of the following formats: - ``projects/PROJECT_ID/inspectTemplates/TEMPLATE_ID`` OR - ``organizations/ORGANIZATION_ID/inspectTemplates/TEMPLATE_ID`` - retention_window_days (int): - Retains data in interaction logging for the - specified number of days. This does not apply to - Cloud logging, which is owned by the user - not - Dialogflow. - User must Set a value lower than Dialogflow's - default 30d TTL. Setting a value higher than - that has no effect. - A missing value or setting to 0 also means we - use Dialogflow's default TTL. - Note: Interaction logging is a limited access - feature. Talk to your Google representative to - check availability for you. - purge_data_types (Sequence[google.cloud.dialogflowcx_v3.types.SecuritySettings.PurgeDataType]): - List of types of data to remove when - retention settings triggers purge. - """ - class RedactionStrategy(proto.Enum): - r"""Defines how we redact data.""" - REDACTION_STRATEGY_UNSPECIFIED = 0 - REDACT_WITH_SERVICE = 1 - - class RedactionScope(proto.Enum): - r"""Defines what types of data to redact.""" - REDACTION_SCOPE_UNSPECIFIED = 0 - REDACT_DISK_STORAGE = 2 - - class PurgeDataType(proto.Enum): - r"""Type of data we purge after retention settings triggers - purge. - """ - PURGE_DATA_TYPE_UNSPECIFIED = 0 - DIALOGFLOW_HISTORY = 1 - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - redaction_strategy = proto.Field( - proto.ENUM, - number=3, - enum=RedactionStrategy, - ) - redaction_scope = proto.Field( - proto.ENUM, - number=4, - enum=RedactionScope, - ) - inspect_template = proto.Field( - proto.STRING, - number=9, - ) - retention_window_days = proto.Field( - proto.INT32, - number=6, - oneof='data_retention', - ) - purge_data_types = proto.RepeatedField( - proto.ENUM, - number=8, - enum=PurgeDataType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session.py deleted file mode 100644 index c8f12205..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session.py +++ /dev/null @@ -1,1167 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import audio_config -from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import response_message -from google.cloud.dialogflowcx_v3.types import session_entity_type -from google.protobuf import duration_pb2 # 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.cx.v3', - manifest={ - 'DetectIntentRequest', - 'DetectIntentResponse', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'QueryParameters', - 'QueryInput', - 'QueryResult', - 'TextInput', - 'IntentInput', - 'AudioInput', - 'EventInput', - 'DtmfInput', - 'Match', - 'MatchIntentRequest', - 'MatchIntentResponse', - 'FulfillIntentRequest', - 'FulfillIntentResponse', - 'SentimentAnalysisResult', - }, -) - - -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//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. It's up to the API caller to choose an - appropriate ``Session ID``. It can be a random number or - some type of session identifiers (preferably hashed). The - length of the ``Session ID`` must not exceed 36 characters. - - For more information, see the `sessions - guide `__. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - query_params (google.cloud.dialogflowcx_v3.types.QueryParameters): - The parameters of this query. - query_input (google.cloud.dialogflowcx_v3.types.QueryInput): - Required. The input specification. - output_audio_config (google.cloud.dialogflowcx_v3.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate the output audio. - """ - - session = proto.Field( - proto.STRING, - number=1, - ) - query_params = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=4, - message=audio_config.OutputAudioConfig, - ) - - -class DetectIntentResponse(proto.Message): - r"""The message returned from the DetectIntent method. - Attributes: - response_id (str): - Output only. 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.dialogflowcx_v3.types.QueryResult): - The result of the conversational query. - 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.response_messages``][google.cloud.dialogflow.cx.v3.QueryResult.response_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.dialogflowcx_v3.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', - ) - output_audio = proto.Field( - proto.BYTES, - number=4, - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=5, - message=audio_config.OutputAudioConfig, - ) - - -class StreamingDetectIntentRequest(proto.Message): - r"""The top-level message sent by the client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3.Sessions.StreamingDetectIntent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it should also - contain - [output_audio_config][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.output_audio_config]. - - 2. If - [query_input][google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio.config][google.cloud.dialogflow.cx.v3.AudioInput.config], - all subsequent messages must contain - [query_input.audio.audio][google.cloud.dialogflow.cx.v3.AudioInput.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.cx.v3.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): - The name of the session this query is sent to. Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. It's up to the API caller to choose an - appropriate ``Session ID``. It can be a random number or - some type of session identifiers (preferably hashed). The - length of the ``Session ID`` must not exceed 36 characters. - Note: session must be set in the first request. - - For more information, see the `sessions - guide `__. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - query_params (google.cloud.dialogflowcx_v3.types.QueryParameters): - The parameters of this query. - query_input (google.cloud.dialogflowcx_v3.types.QueryInput): - Required. The input specification. - output_audio_config (google.cloud.dialogflowcx_v3.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate the output audio. - """ - - session = proto.Field( - proto.STRING, - number=1, - ) - query_params = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=4, - message=audio_config.OutputAudioConfig, - ) - - -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. If ``enable_partial_response`` is true, the following N messages - (currently 1 <= N <= 4) contain ``detect_intent_response``. The - first (N-1) ``detect_intent_response``\ s will have - ``response_type`` set to ``PARTIAL``. The last - ``detect_intent_response`` has ``response_type`` set to - ``FINAL``. If ``response_type`` is false, response stream only - contains the final ``detect_intent_response``. - - Attributes: - recognition_result (google.cloud.dialogflowcx_v3.types.StreamingRecognitionResult): - The result of speech recognition. - detect_intent_response (google.cloud.dialogflowcx_v3.types.DetectIntentResponse): - The response from detect intent. - """ - - recognition_result = proto.Field( - proto.MESSAGE, - number=1, - oneof='response', - message='StreamingRecognitionResult', - ) - detect_intent_response = proto.Field( - proto.MESSAGE, - number=2, - oneof='response', - message='DetectIntentResponse', - ) - - -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.dialogflowcx_v3.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.dialogflowcx_v3.types.SpeechWordInfo]): - Word-specific information for the words recognized by Speech - in - [transcript][google.cloud.dialogflow.cx.v3.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, - ) - stability = proto.Field( - proto.FLOAT, - number=6, - ) - speech_word_info = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=audio_config.SpeechWordInfo, - ) - speech_end_offset = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - - -class QueryParameters(proto.Message): - r"""Represents the parameters of a conversational query. - Attributes: - time_zone (str): - The time zone of this conversational query from the `time - zone database `__, e.g., - America/New_York, Europe/Paris. If not provided, the time - zone specified in the agent is used. - geo_location (google.type.latlng_pb2.LatLng): - The geo location of this conversational - query. - session_entity_types (Sequence[google.cloud.dialogflowcx_v3.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 into the webhook - associated with the agent. Arbitrary JSON objects are - supported. Some integrations that query a Dialogflow agent - may provide additional information in the payload. In - particular, for the Dialogflow Phone Gateway integration, - this field has the form: - - :: - - { - "telephony": { - "caller_id": "+18558363987" - } - } - parameters (google.protobuf.struct_pb2.Struct): - Additional parameters to be put into [session - parameters][SessionInfo.parameters]. To remove a parameter - from the session, clients should explicitly set the - parameter value to null. - - You can reference the session parameters in the agent with - the following format: $session.params.parameter-id. - - 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 - current_page (str): - The unique identifier of the - [page][google.cloud.dialogflow.cx.v3.Page] to override the - [current page][QueryResult.current_page] in the session. - Format: - ``projects//locations//agents//pages/``. - - If ``current_page`` is specified, the previous state of the - session will be ignored by Dialogflow, including the - [previous page][QueryResult.current_page] and the [previous - session parameters][QueryResult.parameters]. In most cases, - [current_page][google.cloud.dialogflow.cx.v3.QueryParameters.current_page] - and - [parameters][google.cloud.dialogflow.cx.v3.QueryParameters.parameters] - should be configured together to direct a session to a - specific state. - disable_webhook (bool): - Whether to disable webhook calls for this - request. - analyze_query_text_sentiment (bool): - Configures whether sentiment analysis should - be performed. If not provided, sentiment - analysis is not performed. - webhook_headers (Sequence[google.cloud.dialogflowcx_v3.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, - ) - session_entity_types = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=session_entity_type.SessionEntityType, - ) - payload = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - parameters = proto.Field( - proto.MESSAGE, - number=5, - message=struct_pb2.Struct, - ) - current_page = proto.Field( - proto.STRING, - number=6, - ) - disable_webhook = proto.Field( - proto.BOOL, - number=7, - ) - analyze_query_text_sentiment = proto.Field( - proto.BOOL, - number=8, - ) - webhook_headers = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - - -class QueryInput(proto.Message): - r"""Represents the query input. It can contain one of: - 1. A conversational query in the form of text. - - 2. An intent query that specifies which intent to trigger. - 3. Natural language speech audio to be processed. - - 4. An event to be triggered. - - Attributes: - text (google.cloud.dialogflowcx_v3.types.TextInput): - The natural language text to be processed. - intent (google.cloud.dialogflowcx_v3.types.IntentInput): - The intent to be triggered. - audio (google.cloud.dialogflowcx_v3.types.AudioInput): - The natural language speech audio to be - processed. - event (google.cloud.dialogflowcx_v3.types.EventInput): - The event to be triggered. - dtmf (google.cloud.dialogflowcx_v3.types.DtmfInput): - The DTMF event to be handled. - language_code (str): - Required. The language of the input. 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.MESSAGE, - number=2, - oneof='input', - message='TextInput', - ) - intent = proto.Field( - proto.MESSAGE, - number=3, - oneof='input', - message='IntentInput', - ) - audio = proto.Field( - proto.MESSAGE, - number=5, - oneof='input', - message='AudioInput', - ) - event = proto.Field( - proto.MESSAGE, - number=6, - oneof='input', - message='EventInput', - ) - dtmf = proto.Field( - proto.MESSAGE, - number=7, - oneof='input', - message='DtmfInput', - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - - -class QueryResult(proto.Message): - r"""Represents the result of a conversational query. - Attributes: - text (str): - If [natural language - text][google.cloud.dialogflow.cx.v3.TextInput] was provided - as input, this field will contain a copy of the text. - trigger_intent (str): - If an [intent][google.cloud.dialogflow.cx.v3.IntentInput] - was provided as input, this field will contain a copy of the - intent identifier. Format: - ``projects//locations//agents//intents/``. - transcript (str): - If [natural language speech - audio][google.cloud.dialogflow.cx.v3.AudioInput] was - provided as input, this field will contain the transcript - for the audio. - trigger_event (str): - If an [event][google.cloud.dialogflow.cx.v3.EventInput] was - provided as input, this field will contain the name of the - event. - language_code (str): - The language that was triggered during intent detection. See - `Language - Support `__ - for a list of the currently supported language codes. - parameters (google.protobuf.struct_pb2.Struct): - The collected [session - parameters][google.cloud.dialogflow.cx.v3.SessionInfo.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 - response_messages (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage]): - The list of rich messages returned to the - client. Responses vary from simple text messages - to more sophisticated, structured payloads used - to drive complex logic. - webhook_statuses (Sequence[google.rpc.status_pb2.Status]): - The list of webhook call status in the order - of call sequence. - webhook_payloads (Sequence[google.protobuf.struct_pb2.Struct]): - The list of webhook payload in - [WebhookResponse.payload][google.cloud.dialogflow.cx.v3.WebhookResponse.payload], - in the order of call sequence. If some webhook call fails or - doesn't return any payload, an empty ``Struct`` would be - used instead. - current_page (google.cloud.dialogflowcx_v3.types.Page): - The current [Page][google.cloud.dialogflow.cx.v3.Page]. - Some, not all fields are filled in this message, including - but not limited to ``name`` and ``display_name``. - intent (google.cloud.dialogflowcx_v3.types.Intent): - The [Intent][google.cloud.dialogflow.cx.v3.Intent] that - matched the conversational query. Some, not all fields are - filled in this message, including but not limited to: - ``name`` and ``display_name``. This field is deprecated, - please use - [QueryResult.match][google.cloud.dialogflow.cx.v3.QueryResult.match] - instead. - 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. This field is deprecated, please use - [QueryResult.match][google.cloud.dialogflow.cx.v3.QueryResult.match] - instead. - match (google.cloud.dialogflowcx_v3.types.Match): - Intent match result, could be an intent or an - event. - diagnostic_info (google.protobuf.struct_pb2.Struct): - The free-form diagnostic info. For example, - this field could contain webhook call latency. - The string keys of the Struct's fields map can - change without notice. - sentiment_analysis_result (google.cloud.dialogflowcx_v3.types.SentimentAnalysisResult): - The sentiment analyss result, which depends on - [``analyze_query_text_sentiment``] - [google.cloud.dialogflow.cx.v3.QueryParameters.analyze_query_text_sentiment], - specified in the request. - """ - - text = proto.Field( - proto.STRING, - number=1, - oneof='query', - ) - trigger_intent = proto.Field( - proto.STRING, - number=11, - oneof='query', - ) - transcript = proto.Field( - proto.STRING, - number=12, - oneof='query', - ) - trigger_event = proto.Field( - proto.STRING, - number=14, - oneof='query', - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - parameters = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - response_messages = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=response_message.ResponseMessage, - ) - webhook_statuses = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=status_pb2.Status, - ) - webhook_payloads = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - current_page = proto.Field( - proto.MESSAGE, - number=7, - message=page.Page, - ) - intent = proto.Field( - proto.MESSAGE, - number=8, - message=gcdc_intent.Intent, - ) - intent_detection_confidence = proto.Field( - proto.FLOAT, - number=9, - ) - match = proto.Field( - proto.MESSAGE, - number=15, - message='Match', - ) - diagnostic_info = proto.Field( - proto.MESSAGE, - number=10, - message=struct_pb2.Struct, - ) - sentiment_analysis_result = proto.Field( - proto.MESSAGE, - number=17, - message='SentimentAnalysisResult', - ) - - -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. - """ - - text = proto.Field( - proto.STRING, - number=1, - ) - - -class IntentInput(proto.Message): - r"""Represents the intent to trigger programmatically rather than - as a result of natural language processing. - - Attributes: - intent (str): - Required. The unique identifier of the intent. Format: - ``projects//locations//agents//intents/``. - """ - - intent = proto.Field( - proto.STRING, - number=1, - ) - - -class AudioInput(proto.Message): - r"""Represents the natural speech audio to be processed. - Attributes: - config (google.cloud.dialogflowcx_v3.types.InputAudioConfig): - Required. Instructs the speech recognizer how - to process the speech audio. - audio (bytes): - The natural language speech audio to be processed. A single - request can contain up to 1 minute of speech audio data. The - [transcribed - text][google.cloud.dialogflow.cx.v3.QueryResult.transcript] - cannot contain more than 256 bytes. - - For non-streaming audio detect intent, both ``config`` and - ``audio`` must be provided. For streaming audio detect - intent, ``config`` must be provided in the first request and - ``audio`` must be provided in all following requests. - """ - - config = proto.Field( - proto.MESSAGE, - number=1, - message=audio_config.InputAudioConfig, - ) - audio = proto.Field( - proto.BYTES, - number=2, - ) - - -class EventInput(proto.Message): - r"""Represents the event to trigger. - Attributes: - event (str): - Name of the event. - """ - - event = proto.Field( - proto.STRING, - number=1, - ) - - -class DtmfInput(proto.Message): - r"""Represents the input for dtmf event. - Attributes: - digits (str): - The dtmf digits. - finish_digit (str): - The finish digit (if any). - """ - - digits = proto.Field( - proto.STRING, - number=1, - ) - finish_digit = proto.Field( - proto.STRING, - number=2, - ) - - -class Match(proto.Message): - r"""Represents one match result of [MatchIntent][]. - Attributes: - intent (google.cloud.dialogflowcx_v3.types.Intent): - The [Intent][google.cloud.dialogflow.cx.v3.Intent] that - matched the query. Some, not all fields are filled in this - message, including but not limited to: ``name`` and - ``display_name``. Only filled for - [``INTENT``][google.cloud.dialogflow.cx.v3.Match.MatchType] - match type. - event (str): - The event that matched the query. Only filled for - [``EVENT``][google.cloud.dialogflow.cx.v3.Match.MatchType] - match type. - parameters (google.protobuf.struct_pb2.Struct): - The collection of parameters extracted from - the query. - 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 - resolved_input (str): - Final text input which was matched during - MatchIntent. This value can be different from - original input sent in request because of - spelling correction or other processing. - match_type (google.cloud.dialogflowcx_v3.types.Match.MatchType): - Type of this [Match][google.cloud.dialogflow.cx.v3.Match]. - confidence (float): - The confidence of this match. Values range - from 0.0 (completely uncertain) to 1.0 - (completely certain). This value is for - informational purpose only and is only used to - help match the best intent within the - classification threshold. This value may change - for the same end-user expression at any time due - to a model retraining or change in - implementation. - """ - class MatchType(proto.Enum): - r"""Type of a Match.""" - MATCH_TYPE_UNSPECIFIED = 0 - INTENT = 1 - DIRECT_INTENT = 2 - PARAMETER_FILLING = 3 - NO_MATCH = 4 - NO_INPUT = 5 - EVENT = 6 - - intent = proto.Field( - proto.MESSAGE, - number=1, - message=gcdc_intent.Intent, - ) - event = proto.Field( - proto.STRING, - number=6, - ) - parameters = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - resolved_input = proto.Field( - proto.STRING, - number=3, - ) - match_type = proto.Field( - proto.ENUM, - number=4, - enum=MatchType, - ) - confidence = proto.Field( - proto.FLOAT, - number=5, - ) - - -class MatchIntentRequest(proto.Message): - r"""Request of [MatchIntent][]. - Attributes: - session (str): - Required. The name of the session this query is sent to. - Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. It's up to the API caller to choose an - appropriate ``Session ID``. It can be a random number or - some type of session identifiers (preferably hashed). The - length of the ``Session ID`` must not exceed 36 characters. - - For more information, see the `sessions - guide `__. - query_params (google.cloud.dialogflowcx_v3.types.QueryParameters): - The parameters of this query. - query_input (google.cloud.dialogflowcx_v3.types.QueryInput): - Required. The input specification. - """ - - session = proto.Field( - proto.STRING, - number=1, - ) - query_params = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - - -class MatchIntentResponse(proto.Message): - r"""Response of [MatchIntent][]. - Attributes: - text (str): - If [natural language - text][google.cloud.dialogflow.cx.v3.TextInput] was provided - as input, this field will contain a copy of the text. - trigger_intent (str): - If an [intent][google.cloud.dialogflow.cx.v3.IntentInput] - was provided as input, this field will contain a copy of the - intent identifier. Format: - ``projects//locations//agents//intents/``. - transcript (str): - If [natural language speech - audio][google.cloud.dialogflow.cx.v3.AudioInput] was - provided as input, this field will contain the transcript - for the audio. - trigger_event (str): - If an [event][google.cloud.dialogflow.cx.v3.EventInput] was - provided as input, this field will contain a copy of the - event name. - matches (Sequence[google.cloud.dialogflowcx_v3.types.Match]): - Match results, if more than one, ordered - descendingly by the confidence we have that the - particular intent matches the query. - current_page (google.cloud.dialogflowcx_v3.types.Page): - The current [Page][google.cloud.dialogflow.cx.v3.Page]. - Some, not all fields are filled in this message, including - but not limited to ``name`` and ``display_name``. - """ - - text = proto.Field( - proto.STRING, - number=1, - oneof='query', - ) - trigger_intent = proto.Field( - proto.STRING, - number=2, - oneof='query', - ) - transcript = proto.Field( - proto.STRING, - number=3, - oneof='query', - ) - trigger_event = proto.Field( - proto.STRING, - number=6, - oneof='query', - ) - matches = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Match', - ) - current_page = proto.Field( - proto.MESSAGE, - number=5, - message=page.Page, - ) - - -class FulfillIntentRequest(proto.Message): - r"""Request of [FulfillIntent][] - Attributes: - match_intent_request (google.cloud.dialogflowcx_v3.types.MatchIntentRequest): - Must be same as the corresponding MatchIntent - request, otherwise the behavior is undefined. - match (google.cloud.dialogflowcx_v3.types.Match): - The matched intent/event to fulfill. - output_audio_config (google.cloud.dialogflowcx_v3.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate output audio. - """ - - match_intent_request = proto.Field( - proto.MESSAGE, - number=1, - message='MatchIntentRequest', - ) - match = proto.Field( - proto.MESSAGE, - number=2, - message='Match', - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=3, - message=audio_config.OutputAudioConfig, - ) - - -class FulfillIntentResponse(proto.Message): - r"""Response of [FulfillIntent][] - Attributes: - response_id (str): - Output only. 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.dialogflowcx_v3.types.QueryResult): - The result of the conversational query. - 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.response_messages``][google.cloud.dialogflow.cx.v3.QueryResult.response_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.dialogflowcx_v3.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', - ) - output_audio = proto.Field( - proto.BYTES, - number=3, - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=4, - message=audio_config.OutputAudioConfig, - ) - - -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. - - 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/v3/google/cloud/dialogflowcx_v3/types/session_entity_type.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session_entity_type.py deleted file mode 100644 index 251c7b38..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/session_entity_type.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 proto # type: ignore - -from google.cloud.dialogflowcx_v3.types import entity_type -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'SessionEntityType', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'GetSessionEntityTypeRequest', - 'CreateSessionEntityTypeRequest', - 'UpdateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - }, -) - - -class SessionEntityType(proto.Message): - r"""Session entity types are referred to as **User** entity types and - are entities that are built for an individual user such as - favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session level to - extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3.EntityType] at the user session - level (we refer to the entity types defined at the agent level as - "custom entity types"). - - Note: session entity types apply to all queries, regardless of the - language. - - For more information about entity types, see the `Dialogflow - documentation `__. - - Attributes: - name (str): - Required. The unique identifier of the session entity type. - Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - entity_override_mode (google.cloud.dialogflowcx_v3.types.SessionEntityType.EntityOverrideMode): - Required. Indicates whether the additional - data should override or supplement the custom - entity type definition. - entities (Sequence[google.cloud.dialogflowcx_v3.types.EntityType.Entity]): - Required. The collection of entities to - override or supplement the custom entity type. - """ - class EntityOverrideMode(proto.Enum): - r"""The types of modifications for the 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=3, - enum=EntityOverrideMode, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=entity_type.EntityType.Entity, - ) - - -class ListSessionEntityTypesRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. - - Attributes: - parent (str): - Required. The session to list all session entity types from. - Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - 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 ListSessionEntityTypesResponse(proto.Message): - r"""The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3.SessionEntityTypes.ListSessionEntityTypes]. - - Attributes: - session_entity_types (Sequence[google.cloud.dialogflowcx_v3.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.cx.v3.SessionEntityTypes.GetSessionEntityType]. - - Attributes: - name (str): - Required. The name of the session entity type. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateSessionEntityTypeRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3.SessionEntityTypes.CreateSessionEntityType]. - - Attributes: - parent (str): - Required. The session to create a session entity type for. - Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - session_entity_type (google.cloud.dialogflowcx_v3.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.cx.v3.SessionEntityTypes.UpdateSessionEntityType]. - - Attributes: - session_entity_type (google.cloud.dialogflowcx_v3.types.SessionEntityType): - Required. The session entity type to update. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.cx.v3.SessionEntityTypes.DeleteSessionEntityType]. - - Attributes: - name (str): - Required. The name of the session entity type to delete. - Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/test_case.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/test_case.py deleted file mode 100644 index 7649a249..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/test_case.py +++ /dev/null @@ -1,1248 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import flow as gcdc_flow -from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -from google.cloud.dialogflowcx_v3.types import page as gcdc_page -from google.cloud.dialogflowcx_v3.types import response_message -from google.cloud.dialogflowcx_v3.types import session -from google.cloud.dialogflowcx_v3.types import transition_route_group -from google.protobuf import field_mask_pb2 # 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.cx.v3', - manifest={ - 'TestResult', - 'TestCase', - 'TestCaseResult', - 'TestConfig', - 'ConversationTurn', - 'TestRunDifference', - 'TransitionCoverage', - 'TransitionRouteGroupCoverage', - 'IntentCoverage', - 'CalculateCoverageRequest', - 'CalculateCoverageResponse', - 'ListTestCasesRequest', - 'ListTestCasesResponse', - 'BatchDeleteTestCasesRequest', - 'CreateTestCaseRequest', - 'UpdateTestCaseRequest', - 'GetTestCaseRequest', - 'RunTestCaseRequest', - 'RunTestCaseResponse', - 'RunTestCaseMetadata', - 'BatchRunTestCasesRequest', - 'BatchRunTestCasesResponse', - 'BatchRunTestCasesMetadata', - 'TestError', - 'ImportTestCasesRequest', - 'ImportTestCasesResponse', - 'ImportTestCasesMetadata', - 'TestCaseError', - 'ExportTestCasesRequest', - 'ExportTestCasesResponse', - 'ExportTestCasesMetadata', - 'ListTestCaseResultsRequest', - 'ListTestCaseResultsResponse', - 'GetTestCaseResultRequest', - }, -) - - -class TestResult(proto.Enum): - r"""The test result for a test case and an agent environment.""" - TEST_RESULT_UNSPECIFIED = 0 - PASSED = 1 - FAILED = 2 - - -class TestCase(proto.Message): - r"""Represents a test case. - Attributes: - name (str): - The unique identifier of the test case. - [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase] - will populate the name automatically. Otherwise use format: - ``projects//locations//agents/ /testCases/``. - tags (Sequence[str]): - Tags are short descriptions that users may - apply to test cases for organizational and - filtering purposes. Each tag should start with - "#" and has a limit of 30 characters. - display_name (str): - Required. The human-readable name of the test - case, unique within the agent. Limit of 200 - characters. - notes (str): - Additional freeform notes about the test - case. Limit of 400 characters. - test_config (google.cloud.dialogflowcx_v3.types.TestConfig): - Config for the test case. - test_case_conversation_turns (Sequence[google.cloud.dialogflowcx_v3.types.ConversationTurn]): - The conversation turns uttered when the test - case was created, in chronological order. These - include the canonical set of agent utterances - that should occur when the agent is working - properly. - creation_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. When the test was created. - last_test_result (google.cloud.dialogflowcx_v3.types.TestCaseResult): - The latest test result. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - tags = proto.RepeatedField( - proto.STRING, - number=2, - ) - display_name = proto.Field( - proto.STRING, - number=3, - ) - notes = proto.Field( - proto.STRING, - number=4, - ) - test_config = proto.Field( - proto.MESSAGE, - number=13, - message='TestConfig', - ) - test_case_conversation_turns = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='ConversationTurn', - ) - creation_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - last_test_result = proto.Field( - proto.MESSAGE, - number=12, - message='TestCaseResult', - ) - - -class TestCaseResult(proto.Message): - r"""Represents a result from running a test case in an agent - environment. - - Attributes: - name (str): - The resource name for the test case result. Format: - ``projects//locations//agents//testCases/ /results/``. - environment (str): - Environment where the test was run. If not - set, it indicates the draft environment. - conversation_turns (Sequence[google.cloud.dialogflowcx_v3.types.ConversationTurn]): - The conversation turns uttered during the - test case replay in chronological order. - test_result (google.cloud.dialogflowcx_v3.types.TestResult): - Whether the test case passed in the agent - environment. - test_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the test was run. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - environment = proto.Field( - proto.STRING, - number=2, - ) - conversation_turns = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='ConversationTurn', - ) - test_result = proto.Field( - proto.ENUM, - number=4, - enum='TestResult', - ) - test_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -class TestConfig(proto.Message): - r"""Represents configurations for a test case. - Attributes: - tracking_parameters (Sequence[str]): - Session parameters to be compared when - calculating differences. - flow (str): - Flow name. If not set, default start flow is assumed. - Format: - ``projects//locations//agents//flows/``. - """ - - tracking_parameters = proto.RepeatedField( - proto.STRING, - number=1, - ) - flow = proto.Field( - proto.STRING, - number=2, - ) - - -class ConversationTurn(proto.Message): - r"""One interaction between a human and virtual agent. The human - provides some input and the virtual agent provides a response. - - Attributes: - user_input (google.cloud.dialogflowcx_v3.types.ConversationTurn.UserInput): - The user input. - virtual_agent_output (google.cloud.dialogflowcx_v3.types.ConversationTurn.VirtualAgentOutput): - The virtual agent output. - """ - - class UserInput(proto.Message): - r"""The input from the human user. - Attributes: - input (google.cloud.dialogflowcx_v3.types.QueryInput): - Supports [text - input][google.cloud.dialogflow.cx.v3.QueryInput.text], - [event - input][google.cloud.dialogflow.cx.v3.QueryInput.event], - [dtmf input][google.cloud.dialogflow.cx.v3.QueryInput.dtmf] - in the test case. - injected_parameters (google.protobuf.struct_pb2.Struct): - Parameters that need to be injected into the - conversation during intent detection. - is_webhook_enabled (bool): - If webhooks should be allowed to trigger in - response to the user utterance. Often if - parameters are injected, webhooks should not be - enabled. - """ - - input = proto.Field( - proto.MESSAGE, - number=5, - message=session.QueryInput, - ) - injected_parameters = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - is_webhook_enabled = proto.Field( - proto.BOOL, - number=3, - ) - - class VirtualAgentOutput(proto.Message): - r"""The output from the virtual agent. - Attributes: - session_parameters (google.protobuf.struct_pb2.Struct): - The session parameters available to the bot - at this point. - differences (Sequence[google.cloud.dialogflowcx_v3.types.TestRunDifference]): - Output only. If this is part of a [result conversation - turn][TestCaseResult.conversation_turns], the list of - differences between the original run and the replay for this - output, if any. - diagnostic_info (google.protobuf.struct_pb2.Struct): - Required. Input only. The diagnostic - [info][Session.DetectIntentResponse.QueryResult.diagnostic_info] - output for the turn. - triggered_intent (google.cloud.dialogflowcx_v3.types.Intent): - The [Intent][google.cloud.dialogflow.cx.v3.Intent] that - triggered the response. Only name and displayName will be - set. - current_page (google.cloud.dialogflowcx_v3.types.Page): - The [Page][google.cloud.dialogflow.cx.v3.Page] on which the - utterance was spoken. Only name and displayName will be set. - text_responses (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage.Text]): - The - [text][google.cloud.dialogflow.cx.v3.ResponseMessage.Text] - responses from the agent for the turn. - status (google.rpc.status_pb2.Status): - Response error from the agent in the test - result. If set, other output is empty. - """ - - session_parameters = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - differences = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='TestRunDifference', - ) - diagnostic_info = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - triggered_intent = proto.Field( - proto.MESSAGE, - number=7, - message=gcdc_intent.Intent, - ) - current_page = proto.Field( - proto.MESSAGE, - number=8, - message=gcdc_page.Page, - ) - text_responses = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=response_message.ResponseMessage.Text, - ) - status = proto.Field( - proto.MESSAGE, - number=10, - message=status_pb2.Status, - ) - - user_input = proto.Field( - proto.MESSAGE, - number=1, - message=UserInput, - ) - virtual_agent_output = proto.Field( - proto.MESSAGE, - number=2, - message=VirtualAgentOutput, - ) - - -class TestRunDifference(proto.Message): - r"""The description of differences between original and replayed - agent output. - - Attributes: - type_ (google.cloud.dialogflowcx_v3.types.TestRunDifference.DiffType): - The type of diff. - description (str): - A description of the diff, showing the actual - output vs expected output. - """ - class DiffType(proto.Enum): - r"""What part of the message replay differs from the test case.""" - DIFF_TYPE_UNSPECIFIED = 0 - INTENT = 1 - PAGE = 2 - PARAMETERS = 3 - UTTERANCE = 4 - - type_ = proto.Field( - proto.ENUM, - number=1, - enum=DiffType, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - - -class TransitionCoverage(proto.Message): - r"""Transition coverage represents the percentage of all possible - page transitions (page-level transition routes and event - handlers, excluding transition route groups) present within any - of a parent's test cases. - - Attributes: - transitions (Sequence[google.cloud.dialogflowcx_v3.types.TransitionCoverage.Transition]): - The list of Transitions present in the agent. - coverage_score (float): - The percent of transitions in the agent that - are covered. - """ - - class TransitionNode(proto.Message): - r"""The source or target of a transition. - Attributes: - page (google.cloud.dialogflowcx_v3.types.Page): - Indicates a transition to a - [Page][google.cloud.dialogflow.cx.v3.Page]. Only some fields - such as name and displayname will be set. - flow (google.cloud.dialogflowcx_v3.types.Flow): - Indicates a transition to a - [Flow][google.cloud.dialogflow.cx.v3.Flow]. Only some fields - such as name and displayname will be set. - """ - - page = proto.Field( - proto.MESSAGE, - number=1, - oneof='kind', - message=gcdc_page.Page, - ) - flow = proto.Field( - proto.MESSAGE, - number=2, - oneof='kind', - message=gcdc_flow.Flow, - ) - - class Transition(proto.Message): - r"""A transition in a page. - Attributes: - source (google.cloud.dialogflowcx_v3.types.TransitionCoverage.TransitionNode): - The start node of a transition. - index (int): - The index of a transition in the transition - list. Starting from 0. - target (google.cloud.dialogflowcx_v3.types.TransitionCoverage.TransitionNode): - The end node of a transition. - covered (bool): - Whether or not the transition is covered by - at least one of the agent's test cases. - transition_route (google.cloud.dialogflowcx_v3.types.TransitionRoute): - Intent route or condition route. - event_handler (google.cloud.dialogflowcx_v3.types.EventHandler): - Event handler. - """ - - source = proto.Field( - proto.MESSAGE, - number=1, - message='TransitionCoverage.TransitionNode', - ) - index = proto.Field( - proto.INT32, - number=4, - ) - target = proto.Field( - proto.MESSAGE, - number=2, - message='TransitionCoverage.TransitionNode', - ) - covered = proto.Field( - proto.BOOL, - number=3, - ) - transition_route = proto.Field( - proto.MESSAGE, - number=5, - oneof='detail', - message=gcdc_page.TransitionRoute, - ) - event_handler = proto.Field( - proto.MESSAGE, - number=6, - oneof='detail', - message=gcdc_page.EventHandler, - ) - - transitions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Transition, - ) - coverage_score = proto.Field( - proto.FLOAT, - number=2, - ) - - -class TransitionRouteGroupCoverage(proto.Message): - r"""Transition route group coverage represents the percentage of - all possible transition routes present within any of a parent's - test cases. The results are grouped by the transition route - group. - - Attributes: - coverages (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRouteGroupCoverage.Coverage]): - Transition route group coverages. - coverage_score (float): - The percent of transition routes in all the - transition route groups that are covered. - """ - - class Coverage(proto.Message): - r"""Coverage result message for one transition route group. - Attributes: - route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): - Transition route group metadata. Only name - and displayName will be set. - transitions (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRouteGroupCoverage.Coverage.Transition]): - The list of transition routes and coverage in - the transition route group. - coverage_score (float): - The percent of transition routes in the - transition route group that are covered. - """ - - class Transition(proto.Message): - r"""A transition coverage in a transition route group. - Attributes: - transition_route (google.cloud.dialogflowcx_v3.types.TransitionRoute): - Intent route or condition route. - covered (bool): - Whether or not the transition route is - covered by at least one of the agent's test - cases. - """ - - transition_route = proto.Field( - proto.MESSAGE, - number=1, - message=gcdc_page.TransitionRoute, - ) - covered = proto.Field( - proto.BOOL, - number=2, - ) - - route_group = proto.Field( - proto.MESSAGE, - number=1, - message=transition_route_group.TransitionRouteGroup, - ) - transitions = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='TransitionRouteGroupCoverage.Coverage.Transition', - ) - coverage_score = proto.Field( - proto.FLOAT, - number=3, - ) - - coverages = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Coverage, - ) - coverage_score = proto.Field( - proto.FLOAT, - number=2, - ) - - -class IntentCoverage(proto.Message): - r"""Intent coverage represents the percentage of all possible - intents in the agent that are triggered in any of a parent's - test cases. - - Attributes: - intents (Sequence[google.cloud.dialogflowcx_v3.types.IntentCoverage.Intent]): - The list of Intents present in the agent - coverage_score (float): - The percent of intents in the agent that are - covered. - """ - - class Intent(proto.Message): - r"""The agent's intent. - Attributes: - intent (str): - The intent full resource name - covered (bool): - Whether or not the intent is covered by at - least one of the agent's test cases. - """ - - intent = proto.Field( - proto.STRING, - number=1, - ) - covered = proto.Field( - proto.BOOL, - number=2, - ) - - intents = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Intent, - ) - coverage_score = proto.Field( - proto.FLOAT, - number=2, - ) - - -class CalculateCoverageRequest(proto.Message): - r"""The request message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. - - Attributes: - agent (str): - Required. The agent to calculate coverage for. Format: - ``projects//locations//agents/``. - type_ (google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest.CoverageType): - Required. The type of coverage requested. - """ - class CoverageType(proto.Enum): - r"""The type of coverage score requested.""" - COVERAGE_TYPE_UNSPECIFIED = 0 - INTENT = 1 - PAGE_TRANSITION = 2 - TRANSITION_ROUTE_GROUP = 3 - - agent = proto.Field( - proto.STRING, - number=3, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - enum=CoverageType, - ) - - -class CalculateCoverageResponse(proto.Message): - r"""The response message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3.TestCases.CalculateCoverage]. - - Attributes: - agent (str): - The agent to calculate coverage for. Format: - ``projects//locations//agents/``. - intent_coverage (google.cloud.dialogflowcx_v3.types.IntentCoverage): - Intent coverage. - transition_coverage (google.cloud.dialogflowcx_v3.types.TransitionCoverage): - Transition (excluding transition route - groups) coverage. - route_group_coverage (google.cloud.dialogflowcx_v3.types.TransitionRouteGroupCoverage): - Transition route group coverage. - """ - - agent = proto.Field( - proto.STRING, - number=5, - ) - intent_coverage = proto.Field( - proto.MESSAGE, - number=2, - oneof='coverage_type', - message='IntentCoverage', - ) - transition_coverage = proto.Field( - proto.MESSAGE, - number=4, - oneof='coverage_type', - message='TransitionCoverage', - ) - route_group_coverage = proto.Field( - proto.MESSAGE, - number=6, - oneof='coverage_type', - message='TransitionRouteGroupCoverage', - ) - - -class ListTestCasesRequest(proto.Message): - r"""The request message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. - - Attributes: - parent (str): - Required. The agent to list all pages for. Format: - ``projects//locations//agents/``. - page_size (int): - The maximum number of items to return in a - single page. By default 20. Note that when - TestCaseView = FULL, the maximum page size - allowed is 20. When TestCaseView = BASIC, the - maximum page size allowed is 500. - page_token (str): - The next_page_token value returned from a previous list - request. - view (google.cloud.dialogflowcx_v3.types.ListTestCasesRequest.TestCaseView): - Specifies whether response should include all - fields or just the metadata. - """ - class TestCaseView(proto.Enum): - r"""Specifies how much test case information to include in the - response. - """ - TEST_CASE_VIEW_UNSPECIFIED = 0 - BASIC = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - view = proto.Field( - proto.ENUM, - number=4, - enum=TestCaseView, - ) - - -class ListTestCasesResponse(proto.Message): - r"""The response message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3.TestCases.ListTestCases]. - - Attributes: - test_cases (Sequence[google.cloud.dialogflowcx_v3.types.TestCase]): - The list of test cases. 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 - - test_cases = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TestCase', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class BatchDeleteTestCasesRequest(proto.Message): - r"""The request message for - [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchDeleteTestCases]. - - Attributes: - parent (str): - Required. The agent to delete test cases from. Format: - ``projects//locations//agents/``. - names (Sequence[str]): - Required. Format of test case names: - ``projects//locations/ /agents//testCases/``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - names = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateTestCaseRequest(proto.Message): - r"""The request message for - [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3.TestCases.CreateTestCase]. - - Attributes: - parent (str): - Required. The agent to create the test case for. Format: - ``projects//locations//agents/``. - test_case (google.cloud.dialogflowcx_v3.types.TestCase): - Required. The test case to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - test_case = proto.Field( - proto.MESSAGE, - number=2, - message='TestCase', - ) - - -class UpdateTestCaseRequest(proto.Message): - r"""The request message for - [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3.TestCases.UpdateTestCase]. - - Attributes: - test_case (google.cloud.dialogflowcx_v3.types.TestCase): - Required. The test case to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to specify which fields should be - updated. The - [``creationTime``][google.cloud.dialogflow.cx.v3.TestCase.creation_time] - and - [``lastTestResult``][google.cloud.dialogflow.cx.v3.TestCase.last_test_result] - cannot be updated. - """ - - test_case = proto.Field( - proto.MESSAGE, - number=1, - message='TestCase', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetTestCaseRequest(proto.Message): - r"""The request message for - [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3.TestCases.GetTestCase]. - - Attributes: - name (str): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class RunTestCaseRequest(proto.Message): - r"""The request message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. - - Attributes: - name (str): - Required. Format of test case name to run: - ``projects//locations/ /agents//testCases/``. - environment (str): - Optional. Environment name. If not set, draft environment is - assumed. Format: - ``projects//locations//agents//environments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - environment = proto.Field( - proto.STRING, - number=2, - ) - - -class RunTestCaseResponse(proto.Message): - r"""The response message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase]. - - Attributes: - result (google.cloud.dialogflowcx_v3.types.TestCaseResult): - The result. - """ - - result = proto.Field( - proto.MESSAGE, - number=2, - message='TestCaseResult', - ) - - -class RunTestCaseMetadata(proto.Message): - r"""Metadata returned for the - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase] - long running operation. - """ - - -class BatchRunTestCasesRequest(proto.Message): - r"""The request message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. - - Attributes: - parent (str): - Required. Agent name. Format: - ``projects//locations//agents/ ``. - environment (str): - Optional. If not set, draft environment is assumed. Format: - ``projects//locations//agents//environments/``. - test_cases (Sequence[str]): - Required. Format: - ``projects//locations//agents//testCases/``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - environment = proto.Field( - proto.STRING, - number=2, - ) - test_cases = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class BatchRunTestCasesResponse(proto.Message): - r"""The response message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases]. - - Attributes: - results (Sequence[google.cloud.dialogflowcx_v3.types.TestCaseResult]): - The test case results. The detailed [conversation - turns][google.cloud.dialogflow.cx.v3.TestCaseResult.conversation_turns] - are empty in this response. - """ - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TestCaseResult', - ) - - -class BatchRunTestCasesMetadata(proto.Message): - r"""Metadata returned for the - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3.TestCases.BatchRunTestCases] - long running operation. - - Attributes: - errors (Sequence[google.cloud.dialogflowcx_v3.types.TestError]): - The test errors. - """ - - errors = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TestError', - ) - - -class TestError(proto.Message): - r"""Error info for running a test. - Attributes: - test_case (str): - The test case resource name. - status (google.rpc.status_pb2.Status): - The status associated with the test. - test_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the test was completed. - """ - - test_case = proto.Field( - proto.STRING, - number=1, - ) - status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - test_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class ImportTestCasesRequest(proto.Message): - r"""The request message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. - - Attributes: - parent (str): - Required. The agent to import test cases to. Format: - ``projects//locations//agents/``. - gcs_uri (str): - The `Google Cloud - Storage `__ URI to - import test cases from. The format of this URI must be - ``gs:///``. - content (bytes): - Uncompressed raw byte content for test cases. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - gcs_uri = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - content = proto.Field( - proto.BYTES, - number=3, - oneof='source', - ) - - -class ImportTestCasesResponse(proto.Message): - r"""The response message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases]. - - Attributes: - names (Sequence[str]): - The unique identifiers of the new test cases. Format: - ``projects//locations//agents//testCases/``. - """ - - names = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class ImportTestCasesMetadata(proto.Message): - r"""Metadata returned for the - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ImportTestCases] - long running operation. - - Attributes: - errors (Sequence[google.cloud.dialogflowcx_v3.types.TestCaseError]): - Errors for failed test cases. - """ - - errors = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TestCaseError', - ) - - -class TestCaseError(proto.Message): - r"""Error info for importing a test. - Attributes: - test_case (google.cloud.dialogflowcx_v3.types.TestCase): - The test case. - status (google.rpc.status_pb2.Status): - The status associated with the test case. - """ - - test_case = proto.Field( - proto.MESSAGE, - number=1, - message='TestCase', - ) - status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - -class ExportTestCasesRequest(proto.Message): - r"""The request message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. - - Attributes: - parent (str): - Required. The agent where to export test cases from. Format: - ``projects//locations//agents/``. - gcs_uri (str): - The `Google Cloud - Storage `__ URI to - export the test cases to. The format of this URI must be - ``gs:///``. If unspecified, the - serialized test cases is returned inline. - data_format (google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest.DataFormat): - The data format of the exported test cases. If not - specified, ``BLOB`` is assumed. - filter (str): - The filter expression used to filter exported test cases, - see `API Filtering `__. The expression - is case insensitive and supports the following syntax: - - name = [OR name = ] ... - - For example: - - - "name = t1 OR name = t2" matches the test case with the - exact resource name "t1" or "t2". - """ - class DataFormat(proto.Enum): - r"""Data format of the exported test cases.""" - DATA_FORMAT_UNSPECIFIED = 0 - BLOB = 1 - JSON = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - gcs_uri = proto.Field( - proto.STRING, - number=2, - oneof='destination', - ) - data_format = proto.Field( - proto.ENUM, - number=3, - enum=DataFormat, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ExportTestCasesResponse(proto.Message): - r"""The response message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases]. - - Attributes: - gcs_uri (str): - The URI to a file containing the exported test cases. This - field is populated only if ``gcs_uri`` is specified in - [ExportTestCasesRequest][google.cloud.dialogflow.cx.v3.ExportTestCasesRequest]. - content (bytes): - Uncompressed raw byte content for test cases. - """ - - gcs_uri = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - content = proto.Field( - proto.BYTES, - number=2, - oneof='destination', - ) - - -class ExportTestCasesMetadata(proto.Message): - r"""Metadata returned for the - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases] - long running operation. - """ - - -class ListTestCaseResultsRequest(proto.Message): - r"""The request message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. - - Attributes: - parent (str): - Required. The test case to list results for. Format: - ``projects//locations//agents// testCases/``. - Specify a ``-`` as a wildcard for TestCase ID to list - results across multiple test cases. - 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. - filter (str): - The filter expression used to filter test case results. See - `API Filtering `__. - - The expression is case insensitive. Only 'AND' is supported - for logical operators. The supported syntax is listed below - in detail: - - [AND ] ... [AND latest] - - The supported fields and operators are: field operator - ``environment`` ``=``, ``IN`` (Use value ``draft`` for draft - environment) ``test_time`` ``>``, ``<`` - - ``latest`` only returns the latest test result in all - results for each test case. - - Examples: - - - "environment=draft AND latest" matches the latest test - result for each test case in the draft environment. - - "environment IN (e1,e2)" matches any test case results - with an environment resource name of either "e1" or "e2". - - "test_time > 1602540713" matches any test case results - with test time later than a unix timestamp in seconds - 1602540713. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListTestCaseResultsResponse(proto.Message): - r"""The response message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3.TestCases.ListTestCaseResults]. - - Attributes: - test_case_results (Sequence[google.cloud.dialogflowcx_v3.types.TestCaseResult]): - The list of test case results. - 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 - - test_case_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TestCaseResult', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTestCaseResultRequest(proto.Message): - r"""The request message for - [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. - - Attributes: - name (str): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases//results/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/transition_route_group.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/transition_route_group.py deleted file mode 100644 index 134f5761..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/transition_route_group.py +++ /dev/null @@ -1,307 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import page -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'TransitionRouteGroup', - 'ListTransitionRouteGroupsRequest', - 'ListTransitionRouteGroupsResponse', - 'GetTransitionRouteGroupRequest', - 'CreateTransitionRouteGroupRequest', - 'UpdateTransitionRouteGroupRequest', - 'DeleteTransitionRouteGroupRequest', - }, -) - - -class TransitionRouteGroup(proto.Message): - r"""An TransitionRouteGroup represents a group of - [``TransitionRoutes``][google.cloud.dialogflow.cx.v3.TransitionRoute] - to be used by a [Page][google.cloud.dialogflow.cx.v3.Page]. - - Attributes: - name (str): - The unique identifier of the transition route group. - [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup] - populates the name automatically. Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - display_name (str): - Required. The human-readable name of the transition route - group, unique within the - [Agent][google.cloud.dialogflow.cx.v3.Agent]. The display - name can be no longer than 30 characters. - transition_routes (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRoute]): - Transition routes associated with the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - transition_routes = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=page.TransitionRoute, - ) - - -class ListTransitionRouteGroupsRequest(proto.Message): - r"""The request message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. - - Attributes: - parent (str): - Required. The flow to list all transition route groups for. - Format: - ``projects//locations//agents//flows/``. - 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. - language_code (str): - The language to list transition route groups for. The - following fields are language dependent: - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` - - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - - -class ListTransitionRouteGroupsResponse(proto.Message): - r"""The response message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.ListTransitionRouteGroups]. - - Attributes: - transition_route_groups (Sequence[google.cloud.dialogflowcx_v3.types.TransitionRouteGroup]): - The list of transition route groups. There will be a maximum - number of items returned based on the page_size field in the - request. The list may in some cases be empty or contain - fewer entries than page_size even if this isn't the last - page. - 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 - - transition_route_groups = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TransitionRouteGroup', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTransitionRouteGroupRequest(proto.Message): - r"""The request message for - [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.GetTransitionRouteGroup]. - - Attributes: - name (str): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. - Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - language_code (str): - The language to retrieve the transition route group for. The - following fields are language dependent: - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` - - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateTransitionRouteGroupRequest(proto.Message): - r"""The request message for - [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.CreateTransitionRouteGroup]. - - Attributes: - parent (str): - Required. The flow to create an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - for. Format: - ``projects//locations//agents//flows/``. - transition_route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): - Required. The transition route group to - create. - language_code (str): - The language of the following fields in - ``TransitionRouteGroup``: - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` - - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - transition_route_group = proto.Field( - proto.MESSAGE, - number=2, - message='TransitionRouteGroup', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateTransitionRouteGroupRequest(proto.Message): - r"""The request message for - [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.UpdateTransitionRouteGroup]. - - Attributes: - transition_route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): - Required. The transition route group to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The mask to control which fields get updated. - language_code (str): - The language of the following fields in - ``TransitionRouteGroup``: - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` - - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - transition_route_group = proto.Field( - proto.MESSAGE, - number=1, - message='TransitionRouteGroup', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteTransitionRouteGroupRequest(proto.Message): - r"""The request message for - [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroups.DeleteTransitionRouteGroup]. - - Attributes: - name (str): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] - to delete. Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - force (bool): - This field has no effect for transition route group that no - page is using. If the transition route group is referenced - by any page: - - - If ``force`` is set to false, an error will be returned - with message indicating pages that reference the - transition route group. - - If ``force`` is set to true, Dialogflow will remove the - transition route group, as well as any reference to it. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/validation_message.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/validation_message.py deleted file mode 100644 index 83857e1b..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/validation_message.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cx.v3', - manifest={ - 'ValidationMessage', - 'ResourceName', - }, -) - - -class ValidationMessage(proto.Message): - r"""Agent/flow validation message. - Attributes: - resource_type (google.cloud.dialogflowcx_v3.types.ValidationMessage.ResourceType): - The type of the resources where the message - is found. - resources (Sequence[str]): - The names of the resources where the message - is found. - resource_names (Sequence[google.cloud.dialogflowcx_v3.types.ResourceName]): - The resource names of the resources where the - message is found. - severity (google.cloud.dialogflowcx_v3.types.ValidationMessage.Severity): - Indicates the severity of the message. - detail (str): - The message detail. - """ - class ResourceType(proto.Enum): - r"""Resource types.""" - RESOURCE_TYPE_UNSPECIFIED = 0 - AGENT = 1 - INTENT = 2 - INTENT_TRAINING_PHRASE = 8 - INTENT_PARAMETER = 9 - INTENTS = 10 - INTENT_TRAINING_PHRASES = 11 - ENTITY_TYPE = 3 - ENTITY_TYPES = 12 - WEBHOOK = 4 - FLOW = 5 - PAGE = 6 - PAGES = 13 - TRANSITION_ROUTE_GROUP = 7 - - class Severity(proto.Enum): - r"""Severity level.""" - SEVERITY_UNSPECIFIED = 0 - INFO = 1 - WARNING = 2 - ERROR = 3 - - resource_type = proto.Field( - proto.ENUM, - number=1, - enum=ResourceType, - ) - resources = proto.RepeatedField( - proto.STRING, - number=2, - ) - resource_names = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ResourceName', - ) - severity = proto.Field( - proto.ENUM, - number=3, - enum=Severity, - ) - detail = proto.Field( - proto.STRING, - number=4, - ) - - -class ResourceName(proto.Message): - r"""Resource name and display name. - Attributes: - name (str): - Name. - display_name (str): - Display name. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/version.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/version.py deleted file mode 100644 index b5e9868f..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/version.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 proto # type: ignore - -from google.cloud.dialogflowcx_v3.types import flow -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'CreateVersionOperationMetadata', - 'Version', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'GetVersionRequest', - 'CreateVersionRequest', - 'UpdateVersionRequest', - 'DeleteVersionRequest', - 'LoadVersionRequest', - }, -) - - -class CreateVersionOperationMetadata(proto.Message): - r"""Metadata associated with the long running operation for - [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. - - Attributes: - version (str): - Name of the created version. Format: - ``projects//locations//agents//flows//versions/``. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - - -class Version(proto.Message): - r"""Represents a version of a flow. - Attributes: - name (str): - Format: projects//locations//agents//flows//versions/. - Version ID is a self-increasing number generated - by Dialogflow upon version creation. - display_name (str): - Required. The human-readable name of the - version. Limit of 64 characters. - description (str): - The description of the version. The maximum - length is 500 characters. If exceeded, the - request is rejected. - nlu_settings (google.cloud.dialogflowcx_v3.types.NluSettings): - Output only. The NLU settings of the flow at - version creation. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Create time of the version. - state (google.cloud.dialogflowcx_v3.types.Version.State): - Output only. The state of this version. This - field is read-only and cannot be set by create - and update methods. - """ - class State(proto.Enum): - r"""The state of the version.""" - STATE_UNSPECIFIED = 0 - RUNNING = 1 - SUCCEEDED = 2 - FAILED = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - nlu_settings = proto.Field( - proto.MESSAGE, - number=4, - message=flow.NluSettings, - ) - create_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - state = proto.Field( - proto.ENUM, - number=6, - enum=State, - ) - - -class ListVersionsRequest(proto.Message): - r"""The request message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. - - Attributes: - parent (str): - Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] to - list all versions for. Format: - ``projects//locations//agents//flows/``. - page_size (int): - The maximum number of items to return in a - single page. By default 20 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 ListVersionsResponse(proto.Message): - r"""The response message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3.Versions.ListVersions]. - - Attributes: - versions (Sequence[google.cloud.dialogflowcx_v3.types.Version]): - A list of versions. There will be a maximum number of items - returned based on the page_size field in the request. The - list may in some cases be empty or contain fewer entries - than page_size even if this isn't the last page. - 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.cx.v3.Versions.GetVersion]. - - Attributes: - name (str): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3.Version]. Format: - ``projects//locations//agents//flows//versions/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateVersionRequest(proto.Message): - r"""The request message for - [Versions.CreateVersion][google.cloud.dialogflow.cx.v3.Versions.CreateVersion]. - - Attributes: - parent (str): - Required. The [Flow][google.cloud.dialogflow.cx.v3.Flow] to - create an [Version][google.cloud.dialogflow.cx.v3.Version] - for. Format: - ``projects//locations//agents//flows/``. - version (google.cloud.dialogflowcx_v3.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.cx.v3.Versions.UpdateVersion]. - - Attributes: - version (google.cloud.dialogflowcx_v3.types.Version): - Required. The version to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields get updated. - Currently only ``description`` and ``display_name`` can be - 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.cx.v3.Versions.DeleteVersion]. - - Attributes: - name (str): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3.Version] to delete. - Format: - ``projects//locations//agents//flows//versions/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class LoadVersionRequest(proto.Message): - r"""The request message for - [Versions.LoadVersion][google.cloud.dialogflow.cx.v3.Versions.LoadVersion]. - - Attributes: - name (str): - Required. The - [Version][google.cloud.dialogflow.cx.v3.Version] to be - loaded to draft flow. Format: - ``projects//locations//agents//flows//versions/``. - allow_override_agent_resources (bool): - This field is used to prevent accidental overwrite of other - agent resources, which can potentially impact other flow's - behavior. If ``allow_override_agent_resources`` is false, - conflicted agent-level resources will not be overridden - (i.e. intents, entities, webhooks). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - allow_override_agent_resources = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/webhook.py b/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/webhook.py deleted file mode 100644 index 480caa8e..00000000 --- a/owl-bot-staging/v3/google/cloud/dialogflowcx_v3/types/webhook.py +++ /dev/null @@ -1,791 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.types import response_message -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3', - manifest={ - 'Webhook', - 'ListWebhooksRequest', - 'ListWebhooksResponse', - 'GetWebhookRequest', - 'CreateWebhookRequest', - 'UpdateWebhookRequest', - 'DeleteWebhookRequest', - 'WebhookRequest', - 'WebhookResponse', - 'PageInfo', - 'SessionInfo', - }, -) - - -class Webhook(proto.Message): - r"""Webhooks host the developer's business logic. During a - session, webhooks allow the developer to use the data extracted - by Dialogflow's natural language processing to generate dynamic - responses, validate collected data, or trigger actions on the - backend. - - Attributes: - name (str): - The unique identifier of the webhook. Required for the - [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook] - method. - [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook] - populates the name automatically. Format: - ``projects//locations//agents//webhooks/``. - display_name (str): - Required. The human-readable name of the - webhook, unique within the agent. - generic_web_service (google.cloud.dialogflowcx_v3.types.Webhook.GenericWebService): - Configuration for a generic web service. - service_directory (google.cloud.dialogflowcx_v3.types.Webhook.ServiceDirectoryConfig): - Configuration for a `Service - Directory `__ - service. - timeout (google.protobuf.duration_pb2.Duration): - Webhook execution timeout. Execution is - considered failed if Dialogflow doesn't receive - a response from webhook at the end of the - timeout period. Defaults to 5 seconds, maximum - allowed timeout is 30 seconds. - disabled (bool): - Indicates whether the webhook is disabled. - """ - - class GenericWebService(proto.Message): - r"""Represents configuration for a generic web service. - Attributes: - uri (str): - Required. The webhook 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.dialogflowcx_v3.types.Webhook.GenericWebService.RequestHeadersEntry]): - The HTTP request headers to send together - with webhook requests. - """ - - 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, - ) - - class ServiceDirectoryConfig(proto.Message): - r"""Represents configuration for a `Service - Directory `__ service. - - Attributes: - service (str): - Required. The name of `Service - Directory `__ - service. Format: - ``projects//locations//namespaces//services/``. - ``Location ID`` of the service directory must be the same as - the location of the agent. - generic_web_service (google.cloud.dialogflowcx_v3.types.Webhook.GenericWebService): - Generic Service configuration of this - webhook. - """ - - service = proto.Field( - proto.STRING, - number=1, - ) - generic_web_service = proto.Field( - proto.MESSAGE, - number=2, - message='Webhook.GenericWebService', - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - generic_web_service = proto.Field( - proto.MESSAGE, - number=4, - oneof='webhook', - message=GenericWebService, - ) - service_directory = proto.Field( - proto.MESSAGE, - number=7, - oneof='webhook', - message=ServiceDirectoryConfig, - ) - timeout = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - disabled = proto.Field( - proto.BOOL, - number=5, - ) - - -class ListWebhooksRequest(proto.Message): - r"""The request message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. - - Attributes: - parent (str): - Required. The agent to list all webhooks for. Format: - ``projects//locations//agents/``. - 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 ListWebhooksResponse(proto.Message): - r"""The response message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks]. - - Attributes: - webhooks (Sequence[google.cloud.dialogflowcx_v3.types.Webhook]): - The list of webhooks. 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 - - webhooks = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Webhook', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetWebhookRequest(proto.Message): - r"""The request message for - [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3.Webhooks.GetWebhook]. - - Attributes: - name (str): - Required. The name of the webhook. Format: - ``projects//locations//agents//webhooks/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateWebhookRequest(proto.Message): - r"""The request message for - [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.CreateWebhook]. - - Attributes: - parent (str): - Required. The agent to create a webhook for. Format: - ``projects//locations//agents/``. - webhook (google.cloud.dialogflowcx_v3.types.Webhook): - Required. The webhook to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - webhook = proto.Field( - proto.MESSAGE, - number=2, - message='Webhook', - ) - - -class UpdateWebhookRequest(proto.Message): - r"""The request message for - [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3.Webhooks.UpdateWebhook]. - - Attributes: - webhook (google.cloud.dialogflowcx_v3.types.Webhook): - Required. The webhook to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The mask to control which fields get updated. - If the mask is not present, all fields will be - updated. - """ - - webhook = proto.Field( - proto.MESSAGE, - number=1, - message='Webhook', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteWebhookRequest(proto.Message): - r"""The request message for - [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3.Webhooks.DeleteWebhook]. - - Attributes: - name (str): - Required. The name of the webhook to delete. Format: - ``projects//locations//agents//webhooks/``. - force (bool): - This field has no effect for webhook not being used. For - webhooks that are used by pages/flows/transition route - groups: - - - If ``force`` is set to false, an error will be returned - with message indicating the referenced resources. - - If ``force`` is set to true, Dialogflow will remove the - webhook, as well as any references to the webhook (i.e. - [Webhook][google.cloud.dialogflow.cx.v3.Fulfillment.webhook] - and - [tag][google.cloud.dialogflow.cx.v3.Fulfillment.tag]in - fulfillments that point to this webhook will be removed). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -class WebhookRequest(proto.Message): - r"""The request message for a webhook call. The request is sent - as a JSON object and the field names will be presented in camel - cases. - - Attributes: - detect_intent_response_id (str): - Always present. The unique identifier of the - [DetectIntentResponse][google.cloud.dialogflow.cx.v3.DetectIntentResponse] - that will be returned to the API caller. - text (str): - If [natural language - text][google.cloud.dialogflow.cx.v3.TextInput] was provided - as input, this field will contain a copy of the text. - trigger_intent (str): - If an [intent][google.cloud.dialogflow.cx.v3.IntentInput] - was provided as input, this field will contain a copy of the - intent identifier. Format: - ``projects//locations//agents//intents/``. - transcript (str): - If [natural language speech - audio][google.cloud.dialogflow.cx.v3.AudioInput] was - provided as input, this field will contain the transcript - for the audio. - trigger_event (str): - If an [event][google.cloud.dialogflow.cx.v3.EventInput] was - provided as input, this field will contain the name of the - event. - language_code (str): - The language code specified in the [original - request][QueryInput.language_code]. - fulfillment_info (google.cloud.dialogflowcx_v3.types.WebhookRequest.FulfillmentInfo): - Always present. Information about the - fulfillment that triggered this webhook call. - intent_info (google.cloud.dialogflowcx_v3.types.WebhookRequest.IntentInfo): - Information about the last matched intent. - page_info (google.cloud.dialogflowcx_v3.types.PageInfo): - Information about page status. - session_info (google.cloud.dialogflowcx_v3.types.SessionInfo): - Information about session status. - messages (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage]): - The list of rich message responses to present to the user. - Webhook can choose to append or replace this list in - [WebhookResponse.fulfillment_response][google.cloud.dialogflow.cx.v3.WebhookResponse.fulfillment_response]; - payload (google.protobuf.struct_pb2.Struct): - Custom data set in - [QueryParameters.payload][google.cloud.dialogflow.cx.v3.QueryParameters.payload]. - sentiment_analysis_result (google.cloud.dialogflowcx_v3.types.WebhookRequest.SentimentAnalysisResult): - The sentiment analysis result of the current - user request. The field is filled when sentiment - analysis is configured to be enabled for the - request. - """ - - class FulfillmentInfo(proto.Message): - r"""Represents fulfillment information communicated to the - webhook. - - Attributes: - tag (str): - Always present. The tag used to identify - which fulfillment is being called. - """ - - tag = proto.Field( - proto.STRING, - number=1, - ) - - class IntentInfo(proto.Message): - r"""Represents intent information communicated to the webhook. - Attributes: - last_matched_intent (str): - Always present. The unique identifier of the last matched - [intent][google.cloud.dialogflow.cx.v3.Intent]. Format: - ``projects//locations//agents//intents/``. - display_name (str): - Always present. The display name of the last matched - [intent][google.cloud.dialogflow.cx.v3.Intent]. - parameters (Sequence[google.cloud.dialogflowcx_v3.types.WebhookRequest.IntentInfo.ParametersEntry]): - Parameters identified as a result of intent - matching. This is a map of the name of the - identified parameter to the value of the - parameter identified from the user's utterance. - All parameters defined in the matched intent - that are identified will be surfaced here. - confidence (float): - The confidence of the matched intent. Values - range from 0.0 (completely uncertain) to 1.0 - (completely certain). - """ - - class IntentParameterValue(proto.Message): - r"""Represents a value for an intent parameter. - Attributes: - original_value (str): - Always present. Original text value extracted - from user utterance. - resolved_value (google.protobuf.struct_pb2.Value): - Always present. Structured value for the - parameter extracted from user utterance. - """ - - original_value = proto.Field( - proto.STRING, - number=1, - ) - resolved_value = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - last_matched_intent = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=3, - ) - parameters = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='WebhookRequest.IntentInfo.IntentParameterValue', - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - - class SentimentAnalysisResult(proto.Message): - r"""Represents the result of sentiment analysis. - 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, - ) - - detect_intent_response_id = proto.Field( - proto.STRING, - number=1, - ) - text = proto.Field( - proto.STRING, - number=10, - oneof='query', - ) - trigger_intent = proto.Field( - proto.STRING, - number=11, - oneof='query', - ) - transcript = proto.Field( - proto.STRING, - number=12, - oneof='query', - ) - trigger_event = proto.Field( - proto.STRING, - number=14, - oneof='query', - ) - language_code = proto.Field( - proto.STRING, - number=15, - ) - fulfillment_info = proto.Field( - proto.MESSAGE, - number=6, - message=FulfillmentInfo, - ) - intent_info = proto.Field( - proto.MESSAGE, - number=3, - message=IntentInfo, - ) - page_info = proto.Field( - proto.MESSAGE, - number=4, - message='PageInfo', - ) - session_info = proto.Field( - proto.MESSAGE, - number=5, - message='SessionInfo', - ) - messages = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=response_message.ResponseMessage, - ) - payload = proto.Field( - proto.MESSAGE, - number=8, - message=struct_pb2.Struct, - ) - sentiment_analysis_result = proto.Field( - proto.MESSAGE, - number=9, - message=SentimentAnalysisResult, - ) - - -class WebhookResponse(proto.Message): - r"""The response message for a webhook call. - Attributes: - fulfillment_response (google.cloud.dialogflowcx_v3.types.WebhookResponse.FulfillmentResponse): - The fulfillment response to send to the user. - This field can be omitted by the webhook if it - does not intend to send any response to the - user. - page_info (google.cloud.dialogflowcx_v3.types.PageInfo): - Information about page status. This field can - be omitted by the webhook if it does not intend - to modify page status. - session_info (google.cloud.dialogflowcx_v3.types.SessionInfo): - Information about session status. This field - can be omitted by the webhook if it does not - intend to modify session status. - payload (google.protobuf.struct_pb2.Struct): - Value to append directly to - [QueryResult.webhook_payloads][google.cloud.dialogflow.cx.v3.QueryResult.webhook_payloads]. - target_page (str): - The target page to transition to. Format: - ``projects//locations//agents//flows//pages/``. - target_flow (str): - The target flow to transition to. Format: - ``projects//locations//agents//flows/``. - """ - - class FulfillmentResponse(proto.Message): - r"""Represents a fulfillment response to the user. - Attributes: - messages (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage]): - The list of rich message responses to present - to the user. - merge_behavior (google.cloud.dialogflowcx_v3.types.WebhookResponse.FulfillmentResponse.MergeBehavior): - Merge behavior for ``messages``. - """ - class MergeBehavior(proto.Enum): - r"""Defines merge behavior for ``messages``.""" - MERGE_BEHAVIOR_UNSPECIFIED = 0 - APPEND = 1 - REPLACE = 2 - - messages = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=response_message.ResponseMessage, - ) - merge_behavior = proto.Field( - proto.ENUM, - number=2, - enum='WebhookResponse.FulfillmentResponse.MergeBehavior', - ) - - fulfillment_response = proto.Field( - proto.MESSAGE, - number=1, - message=FulfillmentResponse, - ) - page_info = proto.Field( - proto.MESSAGE, - number=2, - message='PageInfo', - ) - session_info = proto.Field( - proto.MESSAGE, - number=3, - message='SessionInfo', - ) - payload = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - target_page = proto.Field( - proto.STRING, - number=5, - oneof='transition', - ) - target_flow = proto.Field( - proto.STRING, - number=6, - oneof='transition', - ) - - -class PageInfo(proto.Message): - r"""Represents page information communicated to and from the - webhook. - - Attributes: - current_page (str): - Always present for - [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. - Ignored for - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - The unique identifier of the current page. Format: - ``projects//locations//agents//flows//pages/``. - form_info (google.cloud.dialogflowcx_v3.types.PageInfo.FormInfo): - Optional for both - [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest] - and - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - Information about the form. - """ - - class FormInfo(proto.Message): - r"""Represents form information. - Attributes: - parameter_info (Sequence[google.cloud.dialogflowcx_v3.types.PageInfo.FormInfo.ParameterInfo]): - Optional for both - [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest] - and - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - The parameters contained in the form. Note that the webhook - cannot add or remove any form parameter. - """ - - class ParameterInfo(proto.Message): - r"""Represents parameter information. - Attributes: - display_name (str): - Always present for - [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. - Required for - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - The human-readable name of the parameter, unique within the - form. This field cannot be modified by the webhook. - required (bool): - Optional for both - [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest] - and - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - Indicates whether the parameter is required. Optional - parameters will not trigger prompts; however, they are - filled if the user specifies them. Required parameters must - be filled before form filling concludes. - state (google.cloud.dialogflowcx_v3.types.PageInfo.FormInfo.ParameterInfo.ParameterState): - Always present for - [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. - Required for - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - The state of the parameter. This field can be set to - [INVALID][google.cloud.dialogflow.cx.v3.PageInfo.FormInfo.ParameterInfo.ParameterState.INVALID] - by the webhook to invalidate the parameter; other values set - by the webhook will be ignored. - value (google.protobuf.struct_pb2.Value): - Optional for both - [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest] - and - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - The value of the parameter. This field can be set by the - webhook to change the parameter value. - just_collected (bool): - Optional for - [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. - Ignored for - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - Indicates if the parameter value was just collected on the - last conversation turn. - """ - class ParameterState(proto.Enum): - r"""Represents the state of a parameter.""" - PARAMETER_STATE_UNSPECIFIED = 0 - EMPTY = 1 - INVALID = 2 - FILLED = 3 - - display_name = proto.Field( - proto.STRING, - number=1, - ) - required = proto.Field( - proto.BOOL, - number=2, - ) - state = proto.Field( - proto.ENUM, - number=3, - enum='PageInfo.FormInfo.ParameterInfo.ParameterState', - ) - value = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Value, - ) - just_collected = proto.Field( - proto.BOOL, - number=5, - ) - - parameter_info = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='PageInfo.FormInfo.ParameterInfo', - ) - - current_page = proto.Field( - proto.STRING, - number=1, - ) - form_info = proto.Field( - proto.MESSAGE, - number=3, - message=FormInfo, - ) - - -class SessionInfo(proto.Message): - r"""Represents session information communicated to and from the - webhook. - - Attributes: - session (str): - Always present for - [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. - Ignored for - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - The unique identifier of the - [session][google.cloud.dialogflow.cx.v3.DetectIntentRequest.session]. - This field can be used by the webhook to identify a session. - Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/`` - if environment is specified. - parameters (Sequence[google.cloud.dialogflowcx_v3.types.SessionInfo.ParametersEntry]): - Optional for - [WebhookRequest][google.cloud.dialogflow.cx.v3.WebhookRequest]. - Optional for - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - All parameters collected from forms and intents during the - session. Parameters can be created, updated, or removed by - the webhook. To remove a parameter from the session, the - webhook should explicitly set the parameter value to null in - [WebhookResponse][google.cloud.dialogflow.cx.v3.WebhookResponse]. - The map is keyed by parameters' display names. - """ - - session = proto.Field( - proto.STRING, - number=1, - ) - parameters = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3/mypy.ini b/owl-bot-staging/v3/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v3/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v3/noxfile.py b/owl-bot-staging/v3/noxfile.py deleted file mode 100644 index 2343cde2..00000000 --- a/owl-bot-staging/v3/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/dialogflowcx_v3/', - '--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/v3/scripts/fixup_dialogflowcx_v3_keywords.py b/owl-bot-staging/v3/scripts/fixup_dialogflowcx_v3_keywords.py deleted file mode 100644 index c341e25f..00000000 --- a/owl-bot-staging/v3/scripts/fixup_dialogflowcx_v3_keywords.py +++ /dev/null @@ -1,264 +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 dialogflowcxCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_delete_test_cases': ('parent', 'names', ), - 'batch_run_test_cases': ('parent', 'test_cases', 'environment', ), - 'calculate_coverage': ('agent', 'type_', ), - 'create_agent': ('parent', 'agent', ), - 'create_entity_type': ('parent', 'entity_type', 'language_code', ), - 'create_environment': ('parent', 'environment', ), - 'create_experiment': ('parent', 'experiment', ), - 'create_flow': ('parent', 'flow', 'language_code', ), - 'create_intent': ('parent', 'intent', 'language_code', ), - 'create_page': ('parent', 'page', 'language_code', ), - 'create_security_settings': ('parent', 'security_settings', ), - 'create_session_entity_type': ('parent', 'session_entity_type', ), - 'create_test_case': ('parent', 'test_case', ), - 'create_transition_route_group': ('parent', 'transition_route_group', 'language_code', ), - 'create_version': ('parent', 'version', ), - 'create_webhook': ('parent', 'webhook', ), - 'delete_agent': ('name', ), - 'delete_entity_type': ('name', 'force', ), - 'delete_environment': ('name', ), - 'delete_experiment': ('name', ), - 'delete_flow': ('name', 'force', ), - 'delete_intent': ('name', ), - 'delete_page': ('name', 'force', ), - 'delete_security_settings': ('name', ), - 'delete_session_entity_type': ('name', ), - 'delete_transition_route_group': ('name', 'force', ), - 'delete_version': ('name', ), - 'delete_webhook': ('name', 'force', ), - 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', ), - 'export_agent': ('name', 'agent_uri', 'environment', ), - 'export_flow': ('name', 'flow_uri', 'include_referenced_flows', ), - 'export_test_cases': ('parent', 'gcs_uri', 'data_format', 'filter', ), - 'fulfill_intent': ('match_intent_request', 'match', 'output_audio_config', ), - 'get_agent': ('name', ), - 'get_agent_validation_result': ('name', 'language_code', ), - 'get_entity_type': ('name', 'language_code', ), - 'get_environment': ('name', ), - 'get_experiment': ('name', ), - 'get_flow': ('name', 'language_code', ), - 'get_flow_validation_result': ('name', 'language_code', ), - 'get_intent': ('name', 'language_code', ), - 'get_page': ('name', 'language_code', ), - 'get_security_settings': ('name', ), - 'get_session_entity_type': ('name', ), - 'get_test_case': ('name', ), - 'get_test_case_result': ('name', ), - 'get_transition_route_group': ('name', 'language_code', ), - 'get_version': ('name', ), - 'get_webhook': ('name', ), - 'import_flow': ('parent', 'flow_uri', 'flow_content', 'import_option', ), - 'import_test_cases': ('parent', 'gcs_uri', 'content', ), - 'list_agents': ('parent', 'page_size', 'page_token', ), - 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_experiments': ('parent', 'page_size', 'page_token', ), - 'list_flows': ('parent', 'page_size', 'page_token', 'language_code', ), - 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), - 'list_pages': ('parent', 'language_code', 'page_size', 'page_token', ), - 'list_security_settings': ('parent', 'page_size', 'page_token', ), - 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), - 'list_test_case_results': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_test_cases': ('parent', 'page_size', 'page_token', 'view', ), - 'list_transition_route_groups': ('parent', 'page_size', 'page_token', 'language_code', ), - 'list_versions': ('parent', 'page_size', 'page_token', ), - 'list_webhooks': ('parent', 'page_size', 'page_token', ), - 'load_version': ('name', 'allow_override_agent_resources', ), - 'lookup_environment_history': ('name', 'page_size', 'page_token', ), - 'match_intent': ('session', 'query_input', 'query_params', ), - 'restore_agent': ('name', 'agent_uri', 'agent_content', 'restore_option', ), - 'run_test_case': ('name', 'environment', ), - 'start_experiment': ('name', ), - 'stop_experiment': ('name', ), - 'streaming_detect_intent': ('query_input', 'session', 'query_params', 'output_audio_config', ), - 'train_flow': ('name', ), - 'update_agent': ('agent', 'update_mask', ), - 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), - 'update_environment': ('environment', 'update_mask', ), - 'update_experiment': ('experiment', 'update_mask', ), - 'update_flow': ('flow', 'update_mask', 'language_code', ), - 'update_intent': ('intent', 'language_code', 'update_mask', ), - 'update_page': ('page', 'language_code', 'update_mask', ), - 'update_security_settings': ('security_settings', 'update_mask', ), - 'update_session_entity_type': ('session_entity_type', 'update_mask', ), - 'update_test_case': ('test_case', 'update_mask', ), - 'update_transition_route_group': ('transition_route_group', 'update_mask', 'language_code', ), - 'update_version': ('version', 'update_mask', ), - 'update_webhook': ('webhook', 'update_mask', ), - 'validate_agent': ('name', 'language_code', ), - 'validate_flow': ('name', 'language_code', ), - } - - 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=dialogflowcxCallTransformer(), -): - """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 dialogflowcx 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/v3/setup.py b/owl-bot-staging/v3/setup.py deleted file mode 100644 index 18e33869..00000000 --- a/owl-bot-staging/v3/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-dialogflowcx', - 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/v3/tests/__init__.py b/owl-bot-staging/v3/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v3/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/v3/tests/unit/__init__.py b/owl-bot-staging/v3/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v3/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/v3/tests/unit/gapic/__init__.py b/owl-bot-staging/v3/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v3/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/v3/tests/unit/gapic/dialogflowcx_v3/__init__.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/__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/v3/tests/unit/gapic/dialogflowcx_v3/test_agents.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_agents.py deleted file mode 100644 index 9c692470..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_agents.py +++ /dev/null @@ -1,3312 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.agents import AgentsAsyncClient -from google.cloud.dialogflowcx_v3.services.agents import AgentsClient -from google.cloud.dialogflowcx_v3.services.agents import pagers -from google.cloud.dialogflowcx_v3.services.agents import transports -from google.cloud.dialogflowcx_v3.services.agents.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.agents.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import agent -from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent -from google.cloud.dialogflowcx_v3.types import flow -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3.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_list_agents(transport: str = 'grpc', request_type=agent.ListAgentsRequest): - 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.list_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.ListAgentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_agents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAgentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_agents_from_dict(): - test_list_agents(request_type=dict) - - -def test_list_agents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AgentsClient( - credentials=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_agents), - '__call__') as call: - client.list_agents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() - - -@pytest.mark.asyncio -async def test_list_agents_async(transport: str = 'grpc_asyncio', request_type=agent.ListAgentsRequest): - 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.list_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_agents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAgentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_agents_async_from_dict(): - await test_list_agents_async(request_type=dict) - - -def test_list_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.ListAgentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_agents), - '__call__') as call: - call.return_value = agent.ListAgentsResponse() - client.list_agents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_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.ListAgentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_agents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse()) - await client.list_agents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_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.list_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.ListAgentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_agents( - parent='parent_value', - ) - - # Establish that the 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_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.list_agents( - agent.ListAgentsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_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.list_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.ListAgentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_list_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.list_agents( - agent.ListAgentsRequest(), - parent='parent_value', - ) - - -def test_list_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.list_agents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.ListAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_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_list_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.list_agents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.ListAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_list_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.list_agents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.ListAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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_list_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.list_agents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.ListAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_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_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( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - ) - response = client.get_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -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( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - )) - response = await client.get_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -@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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_agent), - '__call__') as call: - call.return_value = agent.Agent() - client.get_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) - await client.get_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_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( - 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_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(), - name='name_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( - 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_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(), - name='name_value', - ) - - -def test_create_agent(transport: str = 'grpc', request_type=gcdc_agent.CreateAgentRequest): - 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.create_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - ) - response = client.create_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -def test_create_agent_from_dict(): - test_create_agent(request_type=dict) - - -def test_create_agent_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AgentsClient( - credentials=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_agent), - '__call__') as call: - client.create_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() - - -@pytest.mark.asyncio -async def test_create_agent_async(transport: str = 'grpc_asyncio', request_type=gcdc_agent.CreateAgentRequest): - 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.create_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - )) - response = await client.create_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -@pytest.mark.asyncio -async def test_create_agent_async_from_dict(): - await test_create_agent_async(request_type=dict) - - -def test_create_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 = gcdc_agent.CreateAgentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_agent), - '__call__') as call: - call.return_value = gcdc_agent.Agent() - client.create_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_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 = gcdc_agent.CreateAgentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - await client.create_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_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.create_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_agent( - parent='parent_value', - agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') - - -def test_create_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.create_agent( - gcdc_agent.CreateAgentRequest(), - parent='parent_value', - agent=gcdc_agent.Agent(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_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.create_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_agent( - parent='parent_value', - agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') - - -@pytest.mark.asyncio -async def test_create_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.create_agent( - gcdc_agent.CreateAgentRequest(), - parent='parent_value', - agent=gcdc_agent.Agent(name='name_value'), - ) - - -def test_update_agent(transport: str = 'grpc', request_type=gcdc_agent.UpdateAgentRequest): - 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.update_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - ) - response = client.update_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -def test_update_agent_from_dict(): - test_update_agent(request_type=dict) - - -def test_update_agent_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AgentsClient( - credentials=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_agent), - '__call__') as call: - client.update_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() - - -@pytest.mark.asyncio -async def test_update_agent_async(transport: str = 'grpc_asyncio', request_type=gcdc_agent.UpdateAgentRequest): - 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.update_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - )) - response = await client.update_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -@pytest.mark.asyncio -async def test_update_agent_async_from_dict(): - await test_update_agent_async(request_type=dict) - - -def test_update_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 = gcdc_agent.UpdateAgentRequest() - - request.agent.name = 'agent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_agent), - '__call__') as call: - call.return_value = gcdc_agent.Agent() - client.update_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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.name=agent.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_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 = gcdc_agent.UpdateAgentRequest() - - request.agent.name = 'agent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - await client.update_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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.name=agent.name/value', - ) in kw['metadata'] - - -def test_update_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.update_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_agent( - agent=gcdc_agent.Agent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].agent == gcdc_agent.Agent(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_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.update_agent( - gcdc_agent.UpdateAgentRequest(), - agent=gcdc_agent.Agent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_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.update_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_agent( - agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_agent_flattened_error_async(): - client = AgentsAsyncClient( - credentials=ga_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_agent( - gcdc_agent.UpdateAgentRequest(), - agent=gcdc_agent.Agent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_agent), - '__call__') as call: - call.return_value = None - client.delete_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_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( - 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_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(), - name='name_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( - 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_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(), - name='name_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_agent), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_export_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_agent), - '__call__') as call: - call.return_value = 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', - 'name=name/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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_agent), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.restore_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_agent), - '__call__') as call: - call.return_value = 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', - 'name=name/value', - ) in kw['metadata'] - - -def test_validate_agent(transport: str = 'grpc', request_type=agent.ValidateAgentRequest): - 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.validate_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.AgentValidationResult( - name='name_value', - ) - response = client.validate_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == 'name_value' - - -def test_validate_agent_from_dict(): - test_validate_agent(request_type=dict) - - -def test_validate_agent_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_agent), - '__call__') as call: - client.validate_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() - - -@pytest.mark.asyncio -async def test_validate_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ValidateAgentRequest): - 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.validate_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult( - name='name_value', - )) - response = await client.validate_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_validate_agent_async_from_dict(): - await test_validate_agent_async(request_type=dict) - - -def test_validate_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.ValidateAgentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_agent), - '__call__') as call: - call.return_value = agent.AgentValidationResult() - client.validate_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_validate_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.ValidateAgentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) - await client.validate_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_agent_validation_result(transport: str = 'grpc', request_type=agent.GetAgentValidationResultRequest): - 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_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.AgentValidationResult( - name='name_value', - ) - response = client.get_agent_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == 'name_value' - - -def test_get_agent_validation_result_from_dict(): - test_get_agent_validation_result(request_type=dict) - - -def test_get_agent_validation_result_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AgentsClient( - credentials=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_validation_result), - '__call__') as call: - client.get_agent_validation_result() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() - - -@pytest.mark.asyncio -async def test_get_agent_validation_result_async(transport: str = 'grpc_asyncio', request_type=agent.GetAgentValidationResultRequest): - 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_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult( - name='name_value', - )) - response = await client.get_agent_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_agent_validation_result_async_from_dict(): - await test_get_agent_validation_result_async(request_type=dict) - - -def test_get_agent_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.GetAgentValidationResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_agent_validation_result), - '__call__') as call: - call.return_value = agent.AgentValidationResult() - client.get_agent_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_agent_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.GetAgentValidationResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_agent_validation_result), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) - await client.get_agent_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_agent_validation_result_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_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.AgentValidationResult() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_agent_validation_result( - name='name_value', - ) - - # Establish that the 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_agent_validation_result_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_validation_result( - agent.GetAgentValidationResultRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_agent_validation_result_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_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.AgentValidationResult() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_agent_validation_result( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_agent_validation_result_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_validation_result( - agent.GetAgentValidationResultRequest(), - name='name_value', - ) - - -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.dialogflowcx_v3.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 = ( - 'list_agents', - 'get_agent', - 'create_agent', - 'update_agent', - 'delete_agent', - 'export_agent', - 'restore_agent', - 'validate_agent', - 'get_agent_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.dialogflowcx_v3.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_agents_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - 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.dialogflowcx_v3.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" - location = "clam" - agent = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) - actual = AgentsClient.agent_path(project, location, agent) - assert expected == actual - - -def test_parse_agent_path(): - expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - } - path = AgentsClient.agent_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_agent_path(path) - assert expected == actual - -def test_agent_validation_result_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/validationResult".format(project=project, location=location, agent=agent, ) - actual = AgentsClient.agent_validation_result_path(project, location, agent) - assert expected == actual - - -def test_parse_agent_validation_result_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "agent": "abalone", - } - path = AgentsClient.agent_validation_result_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_agent_validation_result_path(path) - assert expected == actual - -def test_environment_path(): - project = "squid" - location = "clam" - agent = "whelk" - environment = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - actual = AgentsClient.environment_path(project, location, agent, environment) - assert expected == actual - - -def test_parse_environment_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "environment": "mussel", - } - path = AgentsClient.environment_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_environment_path(path) - assert expected == actual - -def test_flow_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = AgentsClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "flow": "octopus", - } - path = AgentsClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_flow_path(path) - assert expected == actual - -def test_flow_validation_result_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - flow = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) - actual = AgentsClient.flow_validation_result_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_validation_result_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "flow": "abalone", - } - path = AgentsClient.flow_validation_result_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_flow_validation_result_path(path) - assert expected == actual - -def test_security_settings_path(): - project = "squid" - location = "clam" - security_settings = "whelk" - expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - actual = AgentsClient.security_settings_path(project, location, security_settings) - assert expected == actual - - -def test_parse_security_settings_path(): - expected = { - "project": "octopus", - "location": "oyster", - "security_settings": "nudibranch", - } - path = AgentsClient.security_settings_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_security_settings_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - 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": "mussel", - } - 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 = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = AgentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - 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 = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AgentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - 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 = "squid" - expected = "projects/{project}".format(project=project, ) - actual = AgentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - 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 = "whelk" - location = "octopus" - 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": "oyster", - "location": "nudibranch", - } - 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/v3/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py deleted file mode 100644 index b143162b..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py +++ /dev/null @@ -1,2418 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.entity_types import EntityTypesAsyncClient -from google.cloud.dialogflowcx_v3.services.entity_types import EntityTypesClient -from google.cloud.dialogflowcx_v3.services.entity_types import pagers -from google.cloud.dialogflowcx_v3.services.entity_types import transports -from google.cloud.dialogflowcx_v3.services.entity_types.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.entity_types.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import entity_type -from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3.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', - ) - - # Establish that the 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_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', - ) - - -@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', - ) - - # Establish that 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_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', - ) - - -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, - redact=True, - ) - response = client.get_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -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, - redact=True, - )) - response = await client.get_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -@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', - ) - - # Establish that the 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_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', - ) - - -@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', - ) - - # Establish that 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_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', - ) - - -def test_create_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - redact=True, - ) - response = client.create_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -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] == gcdc_entity_type.CreateEntityTypeRequest() - - -@pytest.mark.asyncio -async def test_create_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - redact=True, - )) - response = await client.create_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_entity_type( - parent='parent_value', - entity_type=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( - gcdc_entity_type.CreateEntityTypeRequest(), - parent='parent_value', - entity_type=gcdc_entity_type.EntityType(name='name_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 = gcdc_entity_type.EntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( - gcdc_entity_type.CreateEntityTypeRequest(), - parent='parent_value', - entity_type=gcdc_entity_type.EntityType(name='name_value'), - ) - - -def test_update_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - redact=True, - ) - response = client.update_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -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] == gcdc_entity_type.UpdateEntityTypeRequest() - - -@pytest.mark.asyncio -async def test_update_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - redact=True, - )) - response = await client.update_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_entity_type( - entity_type=gcdc_entity_type.EntityType(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcdc_entity_type.EntityType(name='name_value') - assert args[0].update_mask == field_mask_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( - gcdc_entity_type.UpdateEntityTypeRequest(), - entity_type=gcdc_entity_type.EntityType(name='name_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 = gcdc_entity_type.EntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( - gcdc_entity_type.UpdateEntityTypeRequest(), - entity_type=gcdc_entity_type.EntityType(name='name_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_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.dialogflowcx_v3.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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_entity_types_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_entity_types_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - 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.dialogflowcx_v3.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_type_path(): - project = "squid" - location = "clam" - agent = "whelk" - entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - actual = EntityTypesClient.entity_type_path(project, location, agent, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "entity_type": "mussel", - } - 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 = "winkle" - 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": "nautilus", - } - 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 = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = EntityTypesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - 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 = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EntityTypesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - 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 = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = EntityTypesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - 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 = "oyster" - location = "nudibranch" - 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": "cuttlefish", - "location": "mussel", - } - 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/v3/tests/unit/gapic/dialogflowcx_v3/test_environments.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_environments.py deleted file mode 100644 index 0010480a..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_environments.py +++ /dev/null @@ -1,2851 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.environments import EnvironmentsAsyncClient -from google.cloud.dialogflowcx_v3.services.environments import EnvironmentsClient -from google.cloud.dialogflowcx_v3.services.environments import pagers -from google.cloud.dialogflowcx_v3.services.environments import transports -from google.cloud.dialogflowcx_v3.services.environments.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.environments.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import environment -from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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(): - 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.dialogflowcx_v3.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', - display_name='display_name_value', - description='description_value', - ) - response = client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -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', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@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_get_environment_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.get_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.Environment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_environment( - name='name_value', - ) - - # Establish that the 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_environment_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.get_environment( - environment.GetEnvironmentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_environment_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.get_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.Environment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_environment( - 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_environment_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.get_environment( - environment.GetEnvironmentRequest(), - name='name_value', - ) - - -def test_create_environment(transport: str = 'grpc', request_type=gcdc_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 = operations_pb2.Operation(name='operations/spam') - response = client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.CreateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -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] == gcdc_environment.CreateEnvironmentRequest() - - -@pytest.mark.asyncio -async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.CreateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@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 = gcdc_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 = operations_pb2.Operation(name='operations/op') - 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 = gcdc_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(operations_pb2.Operation(name='operations/op')) - 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_create_environment_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.create_environment), - '__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_environment( - parent='parent_value', - environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') - - -def test_create_environment_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.create_environment( - gcdc_environment.CreateEnvironmentRequest(), - parent='parent_value', - environment=gcdc_environment.Environment(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_environment_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.create_environment), - '__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_environment( - parent='parent_value', - environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') - - -@pytest.mark.asyncio -async def test_create_environment_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.create_environment( - gcdc_environment.CreateEnvironmentRequest(), - parent='parent_value', - environment=gcdc_environment.Environment(name='name_value'), - ) - - -def test_update_environment(transport: str = 'grpc', request_type=gcdc_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 = operations_pb2.Operation(name='operations/spam') - response = client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.UpdateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -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] == gcdc_environment.UpdateEnvironmentRequest() - - -@pytest.mark.asyncio -async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.UpdateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@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 = gcdc_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 = operations_pb2.Operation(name='operations/op') - 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 = gcdc_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(operations_pb2.Operation(name='operations/op')) - 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_update_environment_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.update_environment), - '__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_environment( - environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_environment_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.update_environment( - gcdc_environment.UpdateEnvironmentRequest(), - environment=gcdc_environment.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_environment_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.update_environment), - '__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_environment( - environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_environment_flattened_error_async(): - client = EnvironmentsAsyncClient( - credentials=ga_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_environment( - gcdc_environment.UpdateEnvironmentRequest(), - environment=gcdc_environment.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -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_delete_environment_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.delete_environment), - '__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_environment( - 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_environment_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.delete_environment( - environment.DeleteEnvironmentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_environment_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.delete_environment), - '__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_environment( - 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_environment_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.delete_environment( - environment.DeleteEnvironmentRequest(), - name='name_value', - ) - - -def test_lookup_environment_history(transport: str = 'grpc', request_type=environment.LookupEnvironmentHistoryRequest): - 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.lookup_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.LookupEnvironmentHistoryResponse( - next_page_token='next_page_token_value', - ) - response = client.lookup_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.LookupEnvironmentHistoryPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_lookup_environment_history_from_dict(): - test_lookup_environment_history(request_type=dict) - - -def test_lookup_environment_history_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lookup_environment_history), - '__call__') as call: - client.lookup_environment_history() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() - - -@pytest.mark.asyncio -async def test_lookup_environment_history_async(transport: str = 'grpc_asyncio', request_type=environment.LookupEnvironmentHistoryRequest): - 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.lookup_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse( - next_page_token='next_page_token_value', - )) - response = await client.lookup_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.LookupEnvironmentHistoryAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_lookup_environment_history_async_from_dict(): - await test_lookup_environment_history_async(request_type=dict) - - -def test_lookup_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.LookupEnvironmentHistoryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lookup_environment_history), - '__call__') as call: - call.return_value = environment.LookupEnvironmentHistoryResponse() - client.lookup_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_lookup_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.LookupEnvironmentHistoryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lookup_environment_history), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse()) - await client.lookup_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_lookup_environment_history_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.lookup_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.LookupEnvironmentHistoryResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.lookup_environment_history( - name='name_value', - ) - - # Establish that the 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_lookup_environment_history_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.lookup_environment_history( - environment.LookupEnvironmentHistoryRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_lookup_environment_history_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.lookup_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.LookupEnvironmentHistoryResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.lookup_environment_history( - 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_lookup_environment_history_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.lookup_environment_history( - environment.LookupEnvironmentHistoryRequest(), - name='name_value', - ) - - -def test_lookup_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.lookup_environment_history), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[], - next_page_token='def', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', ''), - )), - ) - pager = client.lookup_environment_history(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_lookup_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.lookup_environment_history), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[], - next_page_token='def', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - pages = list(client.lookup_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_lookup_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.lookup_environment_history), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[], - next_page_token='def', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - async_pager = await client.lookup_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.Environment) - for i in responses) - -@pytest.mark.asyncio -async def test_lookup_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.lookup_environment_history), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[], - next_page_token='def', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.lookup_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.dialogflowcx_v3.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', - 'lookup_environment_history', - ) - 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_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.dialogflowcx_v3.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_environments_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (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.dialogflowcx_v3.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_environments_grpc_lro_client(): - client = EnvironmentsClient( - 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_environments_grpc_lro_async_client(): - client = EnvironmentsAsyncClient( - 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_environment_path(): - project = "squid" - location = "clam" - agent = "whelk" - environment = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - actual = EnvironmentsClient.environment_path(project, location, agent, environment) - assert expected == actual - - -def test_parse_environment_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "environment": "mussel", - } - path = EnvironmentsClient.environment_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_environment_path(path) - assert expected == actual - -def test_version_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - version = "squid" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - actual = EnvironmentsClient.version_path(project, location, agent, flow, version) - assert expected == actual - - -def test_parse_version_path(): - expected = { - "project": "clam", - "location": "whelk", - "agent": "octopus", - "flow": "oyster", - "version": "nudibranch", - } - path = EnvironmentsClient.version_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_version_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "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/v3/tests/unit/gapic/dialogflowcx_v3/test_experiments.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_experiments.py deleted file mode 100644 index 670fe879..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_experiments.py +++ /dev/null @@ -1,2911 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.experiments import ExperimentsAsyncClient -from google.cloud.dialogflowcx_v3.services.experiments import ExperimentsClient -from google.cloud.dialogflowcx_v3.services.experiments import pagers -from google.cloud.dialogflowcx_v3.services.experiments import transports -from google.cloud.dialogflowcx_v3.services.experiments.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.experiments.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import experiment -from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # 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(): - 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 ExperimentsClient._get_default_mtls_endpoint(None) is None - assert ExperimentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ExperimentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ExperimentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ExperimentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ExperimentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - ExperimentsClient, - ExperimentsAsyncClient, -]) -def test_experiments_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", [ - ExperimentsClient, - ExperimentsAsyncClient, -]) -def test_experiments_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_experiments_client_get_transport_class(): - transport = ExperimentsClient.get_transport_class() - available_transports = [ - transports.ExperimentsGrpcTransport, - ] - assert transport in available_transports - - transport = ExperimentsClient.get_transport_class("grpc") - assert transport == transports.ExperimentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), - (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient)) -@mock.patch.object(ExperimentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsAsyncClient)) -def test_experiments_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(ExperimentsClient, '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(ExperimentsClient, '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", [ - (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "true"), - (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "false"), - (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient)) -@mock.patch.object(ExperimentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_experiments_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", [ - (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), - (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_experiments_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", [ - (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), - (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_experiments_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_experiments_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ExperimentsClient( - 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_experiments(transport: str = 'grpc', request_type=experiment.ListExperimentsRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.ListExperimentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_experiments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExperimentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_experiments_from_dict(): - test_list_experiments(request_type=dict) - - -def test_list_experiments_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=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_experiments), - '__call__') as call: - client.list_experiments() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() - - -@pytest.mark.asyncio -async def test_list_experiments_async(transport: str = 'grpc_asyncio', request_type=experiment.ListExperimentsRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_experiments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExperimentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_experiments_async_from_dict(): - await test_list_experiments_async(request_type=dict) - - -def test_list_experiments_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.ListExperimentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - call.return_value = experiment.ListExperimentsResponse() - client.list_experiments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_experiments_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.ListExperimentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse()) - await client.list_experiments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_experiments_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.ListExperimentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_experiments( - parent='parent_value', - ) - - # Establish that the 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_experiments_flattened_error(): - client = ExperimentsClient( - credentials=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_experiments( - experiment.ListExperimentsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_experiments_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.ListExperimentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_experiments( - 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_experiments_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_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_experiments( - experiment.ListExperimentsRequest(), - parent='parent_value', - ) - - -def test_list_experiments_pager(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - experiment.Experiment(), - ], - next_page_token='abc', - ), - experiment.ListExperimentsResponse( - experiments=[], - next_page_token='def', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - ], - next_page_token='ghi', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_experiments(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, experiment.Experiment) - for i in results) - -def test_list_experiments_pages(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - experiment.Experiment(), - ], - next_page_token='abc', - ), - experiment.ListExperimentsResponse( - experiments=[], - next_page_token='def', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - ], - next_page_token='ghi', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_experiments(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_experiments_async_pager(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - experiment.Experiment(), - ], - next_page_token='abc', - ), - experiment.ListExperimentsResponse( - experiments=[], - next_page_token='def', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - ], - next_page_token='ghi', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_experiments(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, experiment.Experiment) - for i in responses) - -@pytest.mark.asyncio -async def test_list_experiments_async_pages(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - experiment.Experiment(), - ], - next_page_token='abc', - ), - experiment.ListExperimentsResponse( - experiments=[], - next_page_token='def', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - ], - next_page_token='ghi', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_experiments(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_experiment(transport: str = 'grpc', request_type=experiment.GetExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - ) - response = client.get_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -def test_get_experiment_from_dict(): - test_get_experiment(request_type=dict) - - -def test_get_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=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_experiment), - '__call__') as call: - client.get_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() - - -@pytest.mark.asyncio -async def test_get_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.GetExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - )) - response = await client.get_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -@pytest.mark.asyncio -async def test_get_experiment_async_from_dict(): - await test_get_experiment_async(request_type=dict) - - -def test_get_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.GetExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_experiment), - '__call__') as call: - call.return_value = experiment.Experiment() - client.get_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.GetExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - await client.get_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_experiment( - name='name_value', - ) - - # Establish that the 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_experiment_flattened_error(): - client = ExperimentsClient( - credentials=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_experiment( - experiment.GetExperimentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_experiment( - 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_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_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_experiment( - experiment.GetExperimentRequest(), - name='name_value', - ) - - -def test_create_experiment(transport: str = 'grpc', request_type=gcdc_experiment.CreateExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_experiment.Experiment.State.DRAFT, - ) - response = client.create_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_experiment.Experiment.State.DRAFT - - -def test_create_experiment_from_dict(): - test_create_experiment(request_type=dict) - - -def test_create_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=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_experiment), - '__call__') as call: - client.create_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() - - -@pytest.mark.asyncio -async def test_create_experiment_async(transport: str = 'grpc_asyncio', request_type=gcdc_experiment.CreateExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_experiment.Experiment.State.DRAFT, - )) - response = await client.create_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_experiment.Experiment.State.DRAFT - - -@pytest.mark.asyncio -async def test_create_experiment_async_from_dict(): - await test_create_experiment_async(request_type=dict) - - -def test_create_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_experiment.CreateExperimentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_experiment), - '__call__') as call: - call.return_value = gcdc_experiment.Experiment() - client.create_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_experiment.CreateExperimentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) - await client.create_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_experiment( - parent='parent_value', - experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') - - -def test_create_experiment_flattened_error(): - client = ExperimentsClient( - credentials=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_experiment( - gcdc_experiment.CreateExperimentRequest(), - parent='parent_value', - experiment=gcdc_experiment.Experiment(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_experiment( - parent='parent_value', - experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') - - -@pytest.mark.asyncio -async def test_create_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_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_experiment( - gcdc_experiment.CreateExperimentRequest(), - parent='parent_value', - experiment=gcdc_experiment.Experiment(name='name_value'), - ) - - -def test_update_experiment(transport: str = 'grpc', request_type=gcdc_experiment.UpdateExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_experiment.Experiment.State.DRAFT, - ) - response = client.update_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_experiment.Experiment.State.DRAFT - - -def test_update_experiment_from_dict(): - test_update_experiment(request_type=dict) - - -def test_update_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=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_experiment), - '__call__') as call: - client.update_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() - - -@pytest.mark.asyncio -async def test_update_experiment_async(transport: str = 'grpc_asyncio', request_type=gcdc_experiment.UpdateExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_experiment.Experiment.State.DRAFT, - )) - response = await client.update_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_experiment.Experiment.State.DRAFT - - -@pytest.mark.asyncio -async def test_update_experiment_async_from_dict(): - await test_update_experiment_async(request_type=dict) - - -def test_update_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_experiment.UpdateExperimentRequest() - - request.experiment.name = 'experiment.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_experiment), - '__call__') as call: - call.return_value = gcdc_experiment.Experiment() - client.update_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'experiment.name=experiment.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_experiment.UpdateExperimentRequest() - - request.experiment.name = 'experiment.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) - await client.update_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'experiment.name=experiment.name/value', - ) in kw['metadata'] - - -def test_update_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_experiment( - experiment=gcdc_experiment.Experiment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].experiment == gcdc_experiment.Experiment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_experiment_flattened_error(): - client = ExperimentsClient( - credentials=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_experiment( - gcdc_experiment.UpdateExperimentRequest(), - experiment=gcdc_experiment.Experiment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_experiment( - experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_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_experiment( - gcdc_experiment.UpdateExperimentRequest(), - experiment=gcdc_experiment.Experiment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_experiment(transport: str = 'grpc', request_type=experiment.DeleteExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_experiment_from_dict(): - test_delete_experiment(request_type=dict) - - -def test_delete_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=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_experiment), - '__call__') as call: - client.delete_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() - - -@pytest.mark.asyncio -async def test_delete_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.DeleteExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_experiment_async_from_dict(): - await test_delete_experiment_async(request_type=dict) - - -def test_delete_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.DeleteExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_experiment), - '__call__') as call: - call.return_value = None - client.delete_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.DeleteExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_experiment), - '__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_experiment( - 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_experiment_flattened_error(): - client = ExperimentsClient( - credentials=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_experiment( - experiment.DeleteExperimentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_experiment), - '__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_experiment( - 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_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_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_experiment( - experiment.DeleteExperimentRequest(), - name='name_value', - ) - - -def test_start_experiment(transport: str = 'grpc', request_type=experiment.StartExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - ) - response = client.start_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -def test_start_experiment_from_dict(): - test_start_experiment(request_type=dict) - - -def test_start_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - client.start_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() - - -@pytest.mark.asyncio -async def test_start_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.StartExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - )) - response = await client.start_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -@pytest.mark.asyncio -async def test_start_experiment_async_from_dict(): - await test_start_experiment_async(request_type=dict) - - -def test_start_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.StartExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - call.return_value = experiment.Experiment() - client.start_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.StartExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - await client.start_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.start_experiment( - name='name_value', - ) - - # Establish that the 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_start_experiment_flattened_error(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_experiment( - experiment.StartExperimentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_start_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.start_experiment( - 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_start_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.start_experiment( - experiment.StartExperimentRequest(), - name='name_value', - ) - - -def test_stop_experiment(transport: str = 'grpc', request_type=experiment.StopExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - ) - response = client.stop_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -def test_stop_experiment_from_dict(): - test_stop_experiment(request_type=dict) - - -def test_stop_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - client.stop_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() - - -@pytest.mark.asyncio -async def test_stop_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.StopExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - )) - response = await client.stop_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -@pytest.mark.asyncio -async def test_stop_experiment_async_from_dict(): - await test_stop_experiment_async(request_type=dict) - - -def test_stop_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.StopExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - call.return_value = experiment.Experiment() - client.stop_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.StopExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - await client.stop_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.stop_experiment( - name='name_value', - ) - - # Establish that the 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_stop_experiment_flattened_error(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_experiment( - experiment.StopExperimentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_stop_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.stop_experiment( - 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_stop_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.stop_experiment( - experiment.StopExperimentRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ExperimentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ExperimentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExperimentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ExperimentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExperimentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ExperimentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ExperimentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ExperimentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ExperimentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ExperimentsGrpcTransport, - transports.ExperimentsGrpcAsyncIOTransport, -]) -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 = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ExperimentsGrpcTransport, - ) - -def test_experiments_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ExperimentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_experiments_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ExperimentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_experiments', - 'get_experiment', - 'create_experiment', - 'update_experiment', - 'delete_experiment', - 'start_experiment', - 'stop_experiment', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_experiments_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExperimentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_experiments_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExperimentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_experiments_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExperimentsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_experiments_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ExperimentsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_experiments_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ExperimentsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ExperimentsGrpcTransport, - transports.ExperimentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_experiments_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ExperimentsGrpcTransport, - transports.ExperimentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_experiments_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ExperimentsGrpcTransport, grpc_helpers), - (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_experiments_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ExperimentsGrpcTransport, grpc_helpers), - (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_experiments_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ExperimentsGrpcTransport, grpc_helpers), - (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_experiments_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) -def test_experiments_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = 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_experiments_host_no_port(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_experiments_host_with_port(): - client = ExperimentsClient( - 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_experiments_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ExperimentsGrpcTransport( - 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_experiments_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ExperimentsGrpcAsyncIOTransport( - 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.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) -def test_experiments_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.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) -def test_experiments_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_experiment_path(): - project = "squid" - location = "clam" - agent = "whelk" - environment = "octopus" - experiment = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format(project=project, location=location, agent=agent, environment=environment, experiment=experiment, ) - actual = ExperimentsClient.experiment_path(project, location, agent, environment, experiment) - assert expected == actual - - -def test_parse_experiment_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "environment": "winkle", - "experiment": "nautilus", - } - path = ExperimentsClient.experiment_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.parse_experiment_path(path) - assert expected == actual - -def test_version_path(): - project = "scallop" - location = "abalone" - agent = "squid" - flow = "clam" - version = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - actual = ExperimentsClient.version_path(project, location, agent, flow, version) - assert expected == actual - - -def test_parse_version_path(): - expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - "flow": "cuttlefish", - "version": "mussel", - } - path = ExperimentsClient.version_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.parse_version_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ExperimentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = ExperimentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = ExperimentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = ExperimentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ExperimentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = ExperimentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = ExperimentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = ExperimentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.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 = ExperimentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = ExperimentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.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.ExperimentsTransport, '_prep_wrapped_messages') as prep: - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ExperimentsTransport, '_prep_wrapped_messages') as prep: - transport_class = ExperimentsClient.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/v3/tests/unit/gapic/dialogflowcx_v3/test_flows.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_flows.py deleted file mode 100644 index 3ad96e96..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_flows.py +++ /dev/null @@ -1,3472 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.flows import FlowsAsyncClient -from google.cloud.dialogflowcx_v3.services.flows import FlowsClient -from google.cloud.dialogflowcx_v3.services.flows import pagers -from google.cloud.dialogflowcx_v3.services.flows import transports -from google.cloud.dialogflowcx_v3.services.flows.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.flows.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import flow -from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow -from google.cloud.dialogflowcx_v3.types import fulfillment -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import response_message -from google.cloud.dialogflowcx_v3.types import validation_message -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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(): - 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 FlowsClient._get_default_mtls_endpoint(None) is None - assert FlowsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert FlowsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert FlowsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert FlowsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert FlowsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - FlowsClient, - FlowsAsyncClient, -]) -def test_flows_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", [ - FlowsClient, - FlowsAsyncClient, -]) -def test_flows_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_flows_client_get_transport_class(): - transport = FlowsClient.get_transport_class() - available_transports = [ - transports.FlowsGrpcTransport, - ] - assert transport in available_transports - - transport = FlowsClient.get_transport_class("grpc") - assert transport == transports.FlowsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FlowsClient, transports.FlowsGrpcTransport, "grpc"), - (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(FlowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsClient)) -@mock.patch.object(FlowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsAsyncClient)) -def test_flows_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(FlowsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=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(FlowsClient, '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", [ - (FlowsClient, transports.FlowsGrpcTransport, "grpc", "true"), - (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (FlowsClient, transports.FlowsGrpcTransport, "grpc", "false"), - (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(FlowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsClient)) -@mock.patch.object(FlowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_flows_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", [ - (FlowsClient, transports.FlowsGrpcTransport, "grpc"), - (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_flows_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", [ - (FlowsClient, transports.FlowsGrpcTransport, "grpc"), - (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_flows_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_flows_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3.services.flows.transports.FlowsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = FlowsClient( - 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_flow(transport: str = 'grpc', request_type=gcdc_flow.CreateFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.create_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_create_flow_from_dict(): - test_create_flow(request_type=dict) - - -def test_create_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow), - '__call__') as call: - client.create_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() - - -@pytest.mark.asyncio -async def test_create_flow_async(transport: str = 'grpc_asyncio', request_type=gcdc_flow.CreateFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.create_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_create_flow_async_from_dict(): - await test_create_flow_async(request_type=dict) - - -def test_create_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_flow.CreateFlowRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - call.return_value = gcdc_flow.Flow() - client.create_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_flow.CreateFlowRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - await client.create_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_flow_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_flow( - parent='parent_value', - flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') - - -def test_create_flow_flattened_error(): - client = FlowsClient( - credentials=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_flow( - gcdc_flow.CreateFlowRequest(), - parent='parent_value', - flow=gcdc_flow.Flow(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_flow_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_flow( - parent='parent_value', - flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') - - -@pytest.mark.asyncio -async def test_create_flow_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow( - gcdc_flow.CreateFlowRequest(), - parent='parent_value', - flow=gcdc_flow.Flow(name='name_value'), - ) - - -def test_delete_flow(transport: str = 'grpc', request_type=flow.DeleteFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_flow_from_dict(): - test_delete_flow(request_type=dict) - - -def test_delete_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow), - '__call__') as call: - client.delete_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() - - -@pytest.mark.asyncio -async def test_delete_flow_async(transport: str = 'grpc_asyncio', request_type=flow.DeleteFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_flow_async_from_dict(): - await test_delete_flow_async(request_type=dict) - - -def test_delete_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.DeleteFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - call.return_value = None - client.delete_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.DeleteFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_flow( - name='name_value', - ) - - # Establish that the 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_flow_flattened_error(): - client = FlowsClient( - credentials=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_flow( - flow.DeleteFlowRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_flow_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - # 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_flow( - 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_flow_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow( - flow.DeleteFlowRequest(), - name='name_value', - ) - - -def test_list_flows(transport: str = 'grpc', request_type=flow.ListFlowsRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.ListFlowsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_flows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFlowsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_flows_from_dict(): - test_list_flows(request_type=dict) - - -def test_list_flows_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flows), - '__call__') as call: - client.list_flows() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() - - -@pytest.mark.asyncio -async def test_list_flows_async(transport: str = 'grpc_asyncio', request_type=flow.ListFlowsRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_flows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFlowsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_flows_async_from_dict(): - await test_list_flows_async(request_type=dict) - - -def test_list_flows_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ListFlowsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - call.return_value = flow.ListFlowsResponse() - client.list_flows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_flows_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ListFlowsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse()) - await client.list_flows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_flows_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.ListFlowsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_flows( - parent='parent_value', - ) - - # Establish that the 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_flows_flattened_error(): - client = FlowsClient( - credentials=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_flows( - flow.ListFlowsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_flows_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.ListFlowsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_flows( - 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_flows_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flows( - flow.ListFlowsRequest(), - parent='parent_value', - ) - - -def test_list_flows_pager(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - flow.Flow(), - ], - next_page_token='abc', - ), - flow.ListFlowsResponse( - flows=[], - next_page_token='def', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - ], - next_page_token='ghi', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_flows(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, flow.Flow) - for i in results) - -def test_list_flows_pages(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - flow.Flow(), - ], - next_page_token='abc', - ), - flow.ListFlowsResponse( - flows=[], - next_page_token='def', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - ], - next_page_token='ghi', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - ], - ), - RuntimeError, - ) - pages = list(client.list_flows(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_flows_async_pager(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - flow.Flow(), - ], - next_page_token='abc', - ), - flow.ListFlowsResponse( - flows=[], - next_page_token='def', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - ], - next_page_token='ghi', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_flows(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, flow.Flow) - for i in responses) - -@pytest.mark.asyncio -async def test_list_flows_async_pages(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - flow.Flow(), - ], - next_page_token='abc', - ), - flow.ListFlowsResponse( - flows=[], - next_page_token='def', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - ], - next_page_token='ghi', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_flows(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_flow(transport: str = 'grpc', request_type=flow.GetFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.get_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_get_flow_from_dict(): - test_get_flow(request_type=dict) - - -def test_get_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow), - '__call__') as call: - client.get_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() - - -@pytest.mark.asyncio -async def test_get_flow_async(transport: str = 'grpc_asyncio', request_type=flow.GetFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.get_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_get_flow_async_from_dict(): - await test_get_flow_async(request_type=dict) - - -def test_get_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.GetFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - call.return_value = flow.Flow() - client.get_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.GetFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow()) - await client.get_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.Flow() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_flow( - name='name_value', - ) - - # Establish that the 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_flow_flattened_error(): - client = FlowsClient( - credentials=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_flow( - flow.GetFlowRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_flow_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.Flow() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_flow( - 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_flow_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow( - flow.GetFlowRequest(), - name='name_value', - ) - - -def test_update_flow(transport: str = 'grpc', request_type=gcdc_flow.UpdateFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.update_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_update_flow_from_dict(): - test_update_flow(request_type=dict) - - -def test_update_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow), - '__call__') as call: - client.update_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() - - -@pytest.mark.asyncio -async def test_update_flow_async(transport: str = 'grpc_asyncio', request_type=gcdc_flow.UpdateFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.update_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_update_flow_async_from_dict(): - await test_update_flow_async(request_type=dict) - - -def test_update_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_flow.UpdateFlowRequest() - - request.flow.name = 'flow.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - call.return_value = gcdc_flow.Flow() - client.update_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'flow.name=flow.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_flow.UpdateFlowRequest() - - request.flow.name = 'flow.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - await client.update_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'flow.name=flow.name/value', - ) in kw['metadata'] - - -def test_update_flow_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_flow( - flow=gcdc_flow.Flow(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].flow == gcdc_flow.Flow(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_flow_flattened_error(): - client = FlowsClient( - credentials=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_flow( - gcdc_flow.UpdateFlowRequest(), - flow=gcdc_flow.Flow(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_flow_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_flow( - flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_flow_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow( - gcdc_flow.UpdateFlowRequest(), - flow=gcdc_flow.Flow(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_train_flow(transport: str = 'grpc', request_type=flow.TrainFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.train_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_train_flow_from_dict(): - test_train_flow(request_type=dict) - - -def test_train_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow), - '__call__') as call: - client.train_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() - - -@pytest.mark.asyncio -async def test_train_flow_async(transport: str = 'grpc_asyncio', request_type=flow.TrainFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.train_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_train_flow_async_from_dict(): - await test_train_flow_async(request_type=dict) - - -def test_train_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.TrainFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.train_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_train_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.TrainFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.train_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_train_flow_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.train_flow( - name='name_value', - ) - - # Establish that the 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_train_flow_flattened_error(): - client = FlowsClient( - credentials=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_flow( - flow.TrainFlowRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_train_flow_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - # 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_flow( - 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_train_flow_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow( - flow.TrainFlowRequest(), - name='name_value', - ) - - -def test_validate_flow(transport: str = 'grpc', request_type=flow.ValidateFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.FlowValidationResult( - name='name_value', - ) - response = client.validate_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == 'name_value' - - -def test_validate_flow_from_dict(): - test_validate_flow(request_type=dict) - - -def test_validate_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_flow), - '__call__') as call: - client.validate_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() - - -@pytest.mark.asyncio -async def test_validate_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ValidateFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult( - name='name_value', - )) - response = await client.validate_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_validate_flow_async_from_dict(): - await test_validate_flow_async(request_type=dict) - - -def test_validate_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ValidateFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_flow), - '__call__') as call: - call.return_value = flow.FlowValidationResult() - client.validate_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_validate_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ValidateFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) - await client.validate_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_validation_result(transport: str = 'grpc', request_type=flow.GetFlowValidationResultRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.FlowValidationResult( - name='name_value', - ) - response = client.get_flow_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == 'name_value' - - -def test_get_flow_validation_result_from_dict(): - test_get_flow_validation_result(request_type=dict) - - -def test_get_flow_validation_result_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow_validation_result), - '__call__') as call: - client.get_flow_validation_result() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() - - -@pytest.mark.asyncio -async def test_get_flow_validation_result_async(transport: str = 'grpc_asyncio', request_type=flow.GetFlowValidationResultRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult( - name='name_value', - )) - response = await client.get_flow_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_flow_validation_result_async_from_dict(): - await test_get_flow_validation_result_async(request_type=dict) - - -def test_get_flow_validation_result_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.GetFlowValidationResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - call.return_value = flow.FlowValidationResult() - client.get_flow_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_validation_result_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.GetFlowValidationResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) - await client.get_flow_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_validation_result_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.FlowValidationResult() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_flow_validation_result( - name='name_value', - ) - - # Establish that the 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_flow_validation_result_flattened_error(): - client = FlowsClient( - credentials=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_flow_validation_result( - flow.GetFlowValidationResultRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_flow_validation_result_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.FlowValidationResult() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_flow_validation_result( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_flow_validation_result_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow_validation_result( - flow.GetFlowValidationResultRequest(), - name='name_value', - ) - - -def test_import_flow(transport: str = 'grpc', request_type=flow.ImportFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ImportFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_flow_from_dict(): - test_import_flow(request_type=dict) - - -def test_import_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_flow), - '__call__') as call: - client.import_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ImportFlowRequest() - - -@pytest.mark.asyncio -async def test_import_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ImportFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ImportFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_flow_async_from_dict(): - await test_import_flow_async(request_type=dict) - - -def test_import_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ImportFlowRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_flow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ImportFlowRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_export_flow(transport: str = 'grpc', request_type=flow.ExportFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.export_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ExportFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_export_flow_from_dict(): - test_export_flow(request_type=dict) - - -def test_export_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_flow), - '__call__') as call: - client.export_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ExportFlowRequest() - - -@pytest.mark.asyncio -async def test_export_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ExportFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.export_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ExportFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_flow_async_from_dict(): - await test_export_flow_async(request_type=dict) - - -def test_export_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ExportFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_flow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_export_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ExportFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.export_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.FlowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.FlowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FlowsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.FlowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FlowsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.FlowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = FlowsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.FlowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.FlowsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.FlowsGrpcTransport, - transports.FlowsGrpcAsyncIOTransport, -]) -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 = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.FlowsGrpcTransport, - ) - -def test_flows_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.FlowsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_flows_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3.services.flows.transports.FlowsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.FlowsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_flow', - 'delete_flow', - 'list_flows', - 'get_flow', - 'update_flow', - 'train_flow', - 'validate_flow', - 'get_flow_validation_result', - 'import_flow', - 'export_flow', - ) - 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_flows_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FlowsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_flows_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FlowsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_flows_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FlowsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_flows_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - FlowsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_flows_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - FlowsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FlowsGrpcTransport, - transports.FlowsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_flows_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FlowsGrpcTransport, - transports.FlowsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_flows_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.FlowsGrpcTransport, grpc_helpers), - (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_flows_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.FlowsGrpcTransport, grpc_helpers), - (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_flows_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.FlowsGrpcTransport, grpc_helpers), - (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_flows_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) -def test_flows_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = 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_flows_host_no_port(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_flows_host_with_port(): - client = FlowsClient( - 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_flows_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FlowsGrpcTransport( - 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_flows_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FlowsGrpcAsyncIOTransport( - 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.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) -def test_flows_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.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) -def test_flows_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_flows_grpc_lro_client(): - client = FlowsClient( - 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_flows_grpc_lro_async_client(): - client = FlowsAsyncClient( - 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_flow_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = FlowsClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "flow": "mussel", - } - path = FlowsClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_flow_path(path) - assert expected == actual - -def test_flow_validation_result_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) - actual = FlowsClient.flow_validation_result_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_validation_result_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "flow": "octopus", - } - path = FlowsClient.flow_validation_result_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_flow_validation_result_path(path) - assert expected == actual - -def test_intent_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = FlowsClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "intent": "abalone", - } - path = FlowsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_intent_path(path) - assert expected == actual - -def test_page_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - actual = FlowsClient.page_path(project, location, agent, flow, page) - assert expected == actual - - -def test_parse_page_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "flow": "winkle", - "page": "nautilus", - } - path = FlowsClient.page_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_page_path(path) - assert expected == actual - -def test_transition_route_group_path(): - project = "scallop" - location = "abalone" - agent = "squid" - flow = "clam" - transition_route_group = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - actual = FlowsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) - assert expected == actual - - -def test_parse_transition_route_group_path(): - expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - "flow": "cuttlefish", - "transition_route_group": "mussel", - } - path = FlowsClient.transition_route_group_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_transition_route_group_path(path) - assert expected == actual - -def test_webhook_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - webhook = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = FlowsClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "webhook": "octopus", - } - path = FlowsClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = FlowsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = FlowsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = FlowsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = FlowsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = FlowsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = FlowsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = FlowsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = FlowsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.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 = FlowsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = FlowsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.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.FlowsTransport, '_prep_wrapped_messages') as prep: - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.FlowsTransport, '_prep_wrapped_messages') as prep: - transport_class = FlowsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_intents.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_intents.py deleted file mode 100644 index 30ee2672..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_intents.py +++ /dev/null @@ -1,2429 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.intents import IntentsAsyncClient -from google.cloud.dialogflowcx_v3.services.intents import IntentsClient -from google.cloud.dialogflowcx_v3.services.intents import pagers -from google.cloud.dialogflowcx_v3.services.intents import transports -from google.cloud.dialogflowcx_v3.services.intents.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.intents.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import intent -from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3.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', - ) - - # Establish that the 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_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', - ) - - -@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', - ) - - # Establish that 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_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', - ) - - -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', - priority=898, - is_fallback=True, - description='description_value', - ) - response = client.get_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -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', - priority=898, - is_fallback=True, - description='description_value', - )) - response = await client.get_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -@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', - ) - - # Establish that the 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_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', - ) - - -@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', - ) - - # Establish that 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_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', - ) - - -def test_create_intent(transport: str = 'grpc', request_type=gcdc_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 = gcdc_intent.Intent( - name='name_value', - display_name='display_name_value', - priority=898, - is_fallback=True, - description='description_value', - ) - response = client.create_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.CreateIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -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] == gcdc_intent.CreateIntentRequest() - - -@pytest.mark.asyncio -async def test_create_intent_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_intent.Intent( - name='name_value', - display_name='display_name_value', - priority=898, - is_fallback=True, - description='description_value', - )) - response = await client.create_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.CreateIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -@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 = gcdc_intent.CreateIntentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_intent), - '__call__') as call: - call.return_value = gcdc_intent.Intent() - client.create_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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 = gcdc_intent.CreateIntentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) - await client.create_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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 = gcdc_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=gcdc_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 == gcdc_intent.Intent(name='name_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( - gcdc_intent.CreateIntentRequest(), - parent='parent_value', - intent=gcdc_intent.Intent(name='name_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 = gcdc_intent.Intent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_intent.Intent(name='name_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( - gcdc_intent.CreateIntentRequest(), - parent='parent_value', - intent=gcdc_intent.Intent(name='name_value'), - ) - - -def test_update_intent(transport: str = 'grpc', request_type=gcdc_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 = gcdc_intent.Intent( - name='name_value', - display_name='display_name_value', - priority=898, - is_fallback=True, - description='description_value', - ) - response = client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.UpdateIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -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] == gcdc_intent.UpdateIntentRequest() - - -@pytest.mark.asyncio -async def test_update_intent_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_intent.Intent( - name='name_value', - display_name='display_name_value', - priority=898, - is_fallback=True, - description='description_value', - )) - response = await client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.UpdateIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -@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 = gcdc_intent.UpdateIntentRequest() - - request.intent.name = 'intent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_intent), - '__call__') as call: - call.return_value = gcdc_intent.Intent() - client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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 = gcdc_intent.UpdateIntentRequest() - - request.intent.name = 'intent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) - await client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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 = gcdc_intent.Intent() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_intent( - intent=gcdc_intent.Intent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].intent == gcdc_intent.Intent(name='name_value') - assert args[0].update_mask == field_mask_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( - gcdc_intent.UpdateIntentRequest(), - intent=gcdc_intent.Intent(name='name_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 = gcdc_intent.Intent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_intent.Intent(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].intent == gcdc_intent.Intent(name='name_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( - gcdc_intent.UpdateIntentRequest(), - intent=gcdc_intent.Intent(name='name_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_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.dialogflowcx_v3.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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_intents_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_intents_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - 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.dialogflowcx_v3.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_entity_type_path(): - project = "squid" - location = "clam" - agent = "whelk" - entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - actual = IntentsClient.entity_type_path(project, location, agent, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "entity_type": "mussel", - } - path = IntentsClient.entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_entity_type_path(path) - assert expected == actual - -def test_intent_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - intent = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = IntentsClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "intent": "octopus", - } - 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 = "oyster" - 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": "nudibranch", - } - 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 = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = IntentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - 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 = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = IntentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - 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 = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = IntentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - 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 = "squid" - location = "clam" - 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": "whelk", - "location": "octopus", - } - 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/v3/tests/unit/gapic/dialogflowcx_v3/test_pages.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_pages.py deleted file mode 100644 index fa67219f..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_pages.py +++ /dev/null @@ -1,2504 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.pages import PagesAsyncClient -from google.cloud.dialogflowcx_v3.services.pages import PagesClient -from google.cloud.dialogflowcx_v3.services.pages import pagers -from google.cloud.dialogflowcx_v3.services.pages import transports -from google.cloud.dialogflowcx_v3.services.pages.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.pages.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import fulfillment -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import page as gcdc_page -from google.cloud.dialogflowcx_v3.types import response_message -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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 PagesClient._get_default_mtls_endpoint(None) is None - assert PagesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PagesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PagesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PagesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PagesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - PagesClient, - PagesAsyncClient, -]) -def test_pages_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", [ - PagesClient, - PagesAsyncClient, -]) -def test_pages_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_pages_client_get_transport_class(): - transport = PagesClient.get_transport_class() - available_transports = [ - transports.PagesGrpcTransport, - ] - assert transport in available_transports - - transport = PagesClient.get_transport_class("grpc") - assert transport == transports.PagesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PagesClient, transports.PagesGrpcTransport, "grpc"), - (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PagesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesClient)) -@mock.patch.object(PagesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesAsyncClient)) -def test_pages_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(PagesClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=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(PagesClient, '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", [ - (PagesClient, transports.PagesGrpcTransport, "grpc", "true"), - (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PagesClient, transports.PagesGrpcTransport, "grpc", "false"), - (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PagesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesClient)) -@mock.patch.object(PagesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_pages_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", [ - (PagesClient, transports.PagesGrpcTransport, "grpc"), - (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_pages_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", [ - (PagesClient, transports.PagesGrpcTransport, "grpc"), - (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_pages_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_pages_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3.services.pages.transports.PagesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PagesClient( - 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_pages(transport: str = 'grpc', request_type=page.ListPagesRequest): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_pages), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.ListPagesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_pages(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPagesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_pages_from_dict(): - test_list_pages(request_type=dict) - - -def test_list_pages_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PagesClient( - credentials=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_pages), - '__call__') as call: - client.list_pages() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() - - -@pytest.mark.asyncio -async def test_list_pages_async(transport: str = 'grpc_asyncio', request_type=page.ListPagesRequest): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_pages), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_pages(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPagesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_pages_async_from_dict(): - await test_list_pages_async(request_type=dict) - - -def test_list_pages_field_headers(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.ListPagesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - call.return_value = page.ListPagesResponse() - client.list_pages(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_pages_field_headers_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.ListPagesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse()) - await client.list_pages(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_pages_flattened(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.ListPagesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_pages( - parent='parent_value', - ) - - # Establish that the 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_pages_flattened_error(): - client = PagesClient( - credentials=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_pages( - page.ListPagesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_pages_flattened_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.ListPagesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_pages( - 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_pages_flattened_error_async(): - client = PagesAsyncClient( - credentials=ga_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_pages( - page.ListPagesRequest(), - parent='parent_value', - ) - - -def test_list_pages_pager(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - page.Page(), - ], - next_page_token='abc', - ), - page.ListPagesResponse( - pages=[], - next_page_token='def', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - ], - next_page_token='ghi', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_pages(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, page.Page) - for i in results) - -def test_list_pages_pages(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - page.Page(), - ], - next_page_token='abc', - ), - page.ListPagesResponse( - pages=[], - next_page_token='def', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - ], - next_page_token='ghi', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - ], - ), - RuntimeError, - ) - pages = list(client.list_pages(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_pages_async_pager(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - page.Page(), - ], - next_page_token='abc', - ), - page.ListPagesResponse( - pages=[], - next_page_token='def', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - ], - next_page_token='ghi', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_pages(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, page.Page) - for i in responses) - -@pytest.mark.asyncio -async def test_list_pages_async_pages(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - page.Page(), - ], - next_page_token='abc', - ), - page.ListPagesResponse( - pages=[], - next_page_token='def', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - ], - next_page_token='ghi', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_pages(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_page(transport: str = 'grpc', request_type=page.GetPageRequest): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.get_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_get_page_from_dict(): - test_get_page(request_type=dict) - - -def test_get_page_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PagesClient( - credentials=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_page), - '__call__') as call: - client.get_page() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() - - -@pytest.mark.asyncio -async def test_get_page_async(transport: str = 'grpc_asyncio', request_type=page.GetPageRequest): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.get_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_get_page_async_from_dict(): - await test_get_page_async(request_type=dict) - - -def test_get_page_field_headers(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.GetPageRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_page), - '__call__') as call: - call.return_value = page.Page() - client.get_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_page_field_headers_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.GetPageRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_page), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.Page()) - await client.get_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_page_flattened(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.Page() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_page( - name='name_value', - ) - - # Establish that the 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_page_flattened_error(): - client = PagesClient( - credentials=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_page( - page.GetPageRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_page_flattened_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.Page() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.Page()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_page( - 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_page_flattened_error_async(): - client = PagesAsyncClient( - credentials=ga_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_page( - page.GetPageRequest(), - name='name_value', - ) - - -def test_create_page(transport: str = 'grpc', request_type=gcdc_page.CreatePageRequest): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.create_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_create_page_from_dict(): - test_create_page(request_type=dict) - - -def test_create_page_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PagesClient( - credentials=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_page), - '__call__') as call: - client.create_page() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() - - -@pytest.mark.asyncio -async def test_create_page_async(transport: str = 'grpc_asyncio', request_type=gcdc_page.CreatePageRequest): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.create_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_create_page_async_from_dict(): - await test_create_page_async(request_type=dict) - - -def test_create_page_field_headers(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_page.CreatePageRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_page), - '__call__') as call: - call.return_value = gcdc_page.Page() - client.create_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_page_field_headers_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_page.CreatePageRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_page), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - await client.create_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_page_flattened(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_page( - parent='parent_value', - page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') - - -def test_create_page_flattened_error(): - client = PagesClient( - credentials=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_page( - gcdc_page.CreatePageRequest(), - parent='parent_value', - page=gcdc_page.Page(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_page_flattened_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_page( - parent='parent_value', - page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') - - -@pytest.mark.asyncio -async def test_create_page_flattened_error_async(): - client = PagesAsyncClient( - credentials=ga_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_page( - gcdc_page.CreatePageRequest(), - parent='parent_value', - page=gcdc_page.Page(name='name_value'), - ) - - -def test_update_page(transport: str = 'grpc', request_type=gcdc_page.UpdatePageRequest): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.update_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_update_page_from_dict(): - test_update_page(request_type=dict) - - -def test_update_page_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PagesClient( - credentials=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_page), - '__call__') as call: - client.update_page() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() - - -@pytest.mark.asyncio -async def test_update_page_async(transport: str = 'grpc_asyncio', request_type=gcdc_page.UpdatePageRequest): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.update_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_update_page_async_from_dict(): - await test_update_page_async(request_type=dict) - - -def test_update_page_field_headers(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_page.UpdatePageRequest() - - request.page.name = 'page.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_page), - '__call__') as call: - call.return_value = gcdc_page.Page() - client.update_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'page.name=page.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_page_field_headers_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_page.UpdatePageRequest() - - request.page.name = 'page.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_page), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - await client.update_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'page.name=page.name/value', - ) in kw['metadata'] - - -def test_update_page_flattened(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_page( - page=gcdc_page.Page(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].page == gcdc_page.Page(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_page_flattened_error(): - client = PagesClient( - credentials=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_page( - gcdc_page.UpdatePageRequest(), - page=gcdc_page.Page(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_page_flattened_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_page( - page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_page_flattened_error_async(): - client = PagesAsyncClient( - credentials=ga_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_page( - gcdc_page.UpdatePageRequest(), - page=gcdc_page.Page(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_page(transport: str = 'grpc', request_type=page.DeletePageRequest): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_page_from_dict(): - test_delete_page(request_type=dict) - - -def test_delete_page_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PagesClient( - credentials=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_page), - '__call__') as call: - client.delete_page() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() - - -@pytest.mark.asyncio -async def test_delete_page_async(transport: str = 'grpc_asyncio', request_type=page.DeletePageRequest): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_page_async_from_dict(): - await test_delete_page_async(request_type=dict) - - -def test_delete_page_field_headers(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.DeletePageRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_page), - '__call__') as call: - call.return_value = None - client.delete_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_page_field_headers_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.DeletePageRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_page), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_page_flattened(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_page( - name='name_value', - ) - - # Establish that the 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_page_flattened_error(): - client = PagesClient( - credentials=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_page( - page.DeletePageRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_page_flattened_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_page), - '__call__') as call: - # 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_page( - 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_page_flattened_error_async(): - client = PagesAsyncClient( - credentials=ga_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_page( - page.DeletePageRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PagesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PagesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PagesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PagesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PagesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PagesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PagesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PagesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PagesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PagesGrpcTransport, - transports.PagesGrpcAsyncIOTransport, -]) -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 = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PagesGrpcTransport, - ) - -def test_pages_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PagesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_pages_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3.services.pages.transports.PagesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PagesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_pages', - 'get_page', - 'create_page', - 'update_page', - 'delete_page', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_pages_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PagesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_pages_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PagesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_pages_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PagesTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_pages_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - PagesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_pages_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - PagesClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PagesGrpcTransport, - transports.PagesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_pages_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PagesGrpcTransport, - transports.PagesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_pages_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PagesGrpcTransport, grpc_helpers), - (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_pages_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PagesGrpcTransport, grpc_helpers), - (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_pages_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PagesGrpcTransport, grpc_helpers), - (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_pages_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) -def test_pages_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = 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_pages_host_no_port(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_pages_host_with_port(): - client = PagesClient( - 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_pages_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PagesGrpcTransport( - 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_pages_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PagesGrpcAsyncIOTransport( - 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.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) -def test_pages_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.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) -def test_pages_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_type_path(): - project = "squid" - location = "clam" - agent = "whelk" - entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - actual = PagesClient.entity_type_path(project, location, agent, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "entity_type": "mussel", - } - path = PagesClient.entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_entity_type_path(path) - assert expected == actual - -def test_flow_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = PagesClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "flow": "octopus", - } - path = PagesClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_flow_path(path) - assert expected == actual - -def test_intent_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = PagesClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "intent": "abalone", - } - path = PagesClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_intent_path(path) - assert expected == actual - -def test_page_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - actual = PagesClient.page_path(project, location, agent, flow, page) - assert expected == actual - - -def test_parse_page_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "flow": "winkle", - "page": "nautilus", - } - path = PagesClient.page_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_page_path(path) - assert expected == actual - -def test_transition_route_group_path(): - project = "scallop" - location = "abalone" - agent = "squid" - flow = "clam" - transition_route_group = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - actual = PagesClient.transition_route_group_path(project, location, agent, flow, transition_route_group) - assert expected == actual - - -def test_parse_transition_route_group_path(): - expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - "flow": "cuttlefish", - "transition_route_group": "mussel", - } - path = PagesClient.transition_route_group_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_transition_route_group_path(path) - assert expected == actual - -def test_webhook_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - webhook = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = PagesClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "webhook": "octopus", - } - path = PagesClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PagesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = PagesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = PagesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = PagesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PagesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = PagesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = PagesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = PagesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.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 = PagesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = PagesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.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.PagesTransport, '_prep_wrapped_messages') as prep: - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PagesTransport, '_prep_wrapped_messages') as prep: - transport_class = PagesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py deleted file mode 100644 index 99f04405..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py +++ /dev/null @@ -1,2419 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.security_settings_service import SecuritySettingsServiceAsyncClient -from google.cloud.dialogflowcx_v3.services.security_settings_service import SecuritySettingsServiceClient -from google.cloud.dialogflowcx_v3.services.security_settings_service import pagers -from google.cloud.dialogflowcx_v3.services.security_settings_service import transports -from google.cloud.dialogflowcx_v3.services.security_settings_service.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.security_settings_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import security_settings -from google.cloud.dialogflowcx_v3.types import security_settings as gcdc_security_settings -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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 SecuritySettingsServiceClient._get_default_mtls_endpoint(None) is None - assert SecuritySettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecuritySettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecuritySettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecuritySettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecuritySettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - SecuritySettingsServiceClient, - SecuritySettingsServiceAsyncClient, -]) -def test_security_settings_service_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", [ - SecuritySettingsServiceClient, - SecuritySettingsServiceAsyncClient, -]) -def test_security_settings_service_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_security_settings_service_client_get_transport_class(): - transport = SecuritySettingsServiceClient.get_transport_class() - available_transports = [ - transports.SecuritySettingsServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SecuritySettingsServiceClient.get_transport_class("grpc") - assert transport == transports.SecuritySettingsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), - (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SecuritySettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceClient)) -@mock.patch.object(SecuritySettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceAsyncClient)) -def test_security_settings_service_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(SecuritySettingsServiceClient, '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(SecuritySettingsServiceClient, '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", [ - (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc", "true"), - (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc", "false"), - (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SecuritySettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceClient)) -@mock.patch.object(SecuritySettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_settings_service_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", [ - (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), - (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_settings_service_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", [ - (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), - (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_settings_service_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_security_settings_service_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecuritySettingsServiceClient( - 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_security_settings(transport: str = 'grpc', request_type=gcdc_security_settings.CreateSecuritySettingsRequest): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - retention_window_days=2271, - ) - response = client.create_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -def test_create_security_settings_from_dict(): - test_create_security_settings(request_type=dict) - - -def test_create_security_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecuritySettingsServiceClient( - credentials=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_security_settings), - '__call__') as call: - client.create_security_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() - - -@pytest.mark.asyncio -async def test_create_security_settings_async(transport: str = 'grpc_asyncio', request_type=gcdc_security_settings.CreateSecuritySettingsRequest): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - )) - response = await client.create_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -@pytest.mark.asyncio -async def test_create_security_settings_async_from_dict(): - await test_create_security_settings_async(request_type=dict) - - -def test_create_security_settings_field_headers(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_security_settings.CreateSecuritySettingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_settings), - '__call__') as call: - call.return_value = gcdc_security_settings.SecuritySettings() - client.create_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_settings_field_headers_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_security_settings.CreateSecuritySettingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) - await client.create_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_settings_flattened(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_security_settings( - parent='parent_value', - security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') - - -def test_create_security_settings_flattened_error(): - client = SecuritySettingsServiceClient( - credentials=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_security_settings( - gcdc_security_settings.CreateSecuritySettingsRequest(), - parent='parent_value', - security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_security_settings_flattened_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_security_settings( - parent='parent_value', - security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') - - -@pytest.mark.asyncio -async def test_create_security_settings_flattened_error_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_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_security_settings( - gcdc_security_settings.CreateSecuritySettingsRequest(), - parent='parent_value', - security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), - ) - - -def test_get_security_settings(transport: str = 'grpc', request_type=security_settings.GetSecuritySettingsRequest): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - retention_window_days=2271, - ) - response = client.get_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -def test_get_security_settings_from_dict(): - test_get_security_settings(request_type=dict) - - -def test_get_security_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecuritySettingsServiceClient( - credentials=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_security_settings), - '__call__') as call: - client.get_security_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() - - -@pytest.mark.asyncio -async def test_get_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.GetSecuritySettingsRequest): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - )) - response = await client.get_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -@pytest.mark.asyncio -async def test_get_security_settings_async_from_dict(): - await test_get_security_settings_async(request_type=dict) - - -def test_get_security_settings_field_headers(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.GetSecuritySettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_settings), - '__call__') as call: - call.return_value = security_settings.SecuritySettings() - client.get_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_security_settings_field_headers_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.GetSecuritySettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings()) - await client.get_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_security_settings_flattened(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_security_settings( - name='name_value', - ) - - # Establish that the 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_security_settings_flattened_error(): - client = SecuritySettingsServiceClient( - credentials=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_security_settings( - security_settings.GetSecuritySettingsRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_security_settings_flattened_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.SecuritySettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_security_settings( - 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_security_settings_flattened_error_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_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_security_settings( - security_settings.GetSecuritySettingsRequest(), - name='name_value', - ) - - -def test_update_security_settings(transport: str = 'grpc', request_type=gcdc_security_settings.UpdateSecuritySettingsRequest): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - retention_window_days=2271, - ) - response = client.update_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -def test_update_security_settings_from_dict(): - test_update_security_settings(request_type=dict) - - -def test_update_security_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecuritySettingsServiceClient( - credentials=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_security_settings), - '__call__') as call: - client.update_security_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() - - -@pytest.mark.asyncio -async def test_update_security_settings_async(transport: str = 'grpc_asyncio', request_type=gcdc_security_settings.UpdateSecuritySettingsRequest): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - )) - response = await client.update_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -@pytest.mark.asyncio -async def test_update_security_settings_async_from_dict(): - await test_update_security_settings_async(request_type=dict) - - -def test_update_security_settings_field_headers(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_security_settings.UpdateSecuritySettingsRequest() - - request.security_settings.name = 'security_settings.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_settings), - '__call__') as call: - call.return_value = gcdc_security_settings.SecuritySettings() - client.update_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_settings.name=security_settings.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_settings_field_headers_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_security_settings.UpdateSecuritySettingsRequest() - - request.security_settings.name = 'security_settings.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) - await client.update_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_settings.name=security_settings.name/value', - ) in kw['metadata'] - - -def test_update_security_settings_flattened(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_settings( - security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_security_settings_flattened_error(): - client = SecuritySettingsServiceClient( - credentials=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_security_settings( - gcdc_security_settings.UpdateSecuritySettingsRequest(), - security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_security_settings_flattened_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_settings( - security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_security_settings_flattened_error_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_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_security_settings( - gcdc_security_settings.UpdateSecuritySettingsRequest(), - security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_list_security_settings(transport: str = 'grpc', request_type=security_settings.ListSecuritySettingsRequest): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.ListSecuritySettingsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecuritySettingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_security_settings_from_dict(): - test_list_security_settings(request_type=dict) - - -def test_list_security_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecuritySettingsServiceClient( - credentials=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_security_settings), - '__call__') as call: - client.list_security_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() - - -@pytest.mark.asyncio -async def test_list_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.ListSecuritySettingsRequest): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecuritySettingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_security_settings_async_from_dict(): - await test_list_security_settings_async(request_type=dict) - - -def test_list_security_settings_field_headers(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.ListSecuritySettingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - call.return_value = security_settings.ListSecuritySettingsResponse() - client.list_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_settings_field_headers_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.ListSecuritySettingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse()) - await client.list_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_settings_flattened(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.ListSecuritySettingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_security_settings( - parent='parent_value', - ) - - # Establish that the 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_security_settings_flattened_error(): - client = SecuritySettingsServiceClient( - credentials=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_security_settings( - security_settings.ListSecuritySettingsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_security_settings_flattened_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.ListSecuritySettingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_security_settings( - 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_security_settings_flattened_error_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_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_security_settings( - security_settings.ListSecuritySettingsRequest(), - parent='parent_value', - ) - - -def test_list_security_settings_pager(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - next_page_token='abc', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[], - next_page_token='def', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - ], - next_page_token='ghi', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_security_settings(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, security_settings.SecuritySettings) - for i in results) - -def test_list_security_settings_pages(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - next_page_token='abc', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[], - next_page_token='def', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - ], - next_page_token='ghi', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - ), - RuntimeError, - ) - pages = list(client.list_security_settings(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_security_settings_async_pager(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - next_page_token='abc', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[], - next_page_token='def', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - ], - next_page_token='ghi', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_security_settings(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, security_settings.SecuritySettings) - for i in responses) - -@pytest.mark.asyncio -async def test_list_security_settings_async_pages(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - next_page_token='abc', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[], - next_page_token='def', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - ], - next_page_token='ghi', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_security_settings(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_delete_security_settings(transport: str = 'grpc', request_type=security_settings.DeleteSecuritySettingsRequest): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_security_settings_from_dict(): - test_delete_security_settings(request_type=dict) - - -def test_delete_security_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecuritySettingsServiceClient( - credentials=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_security_settings), - '__call__') as call: - client.delete_security_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() - - -@pytest.mark.asyncio -async def test_delete_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.DeleteSecuritySettingsRequest): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_security_settings_async_from_dict(): - await test_delete_security_settings_async(request_type=dict) - - -def test_delete_security_settings_field_headers(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.DeleteSecuritySettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_settings), - '__call__') as call: - call.return_value = None - client.delete_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_security_settings_field_headers_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.DeleteSecuritySettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_security_settings_flattened(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_settings), - '__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_security_settings( - 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_security_settings_flattened_error(): - client = SecuritySettingsServiceClient( - credentials=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_security_settings( - security_settings.DeleteSecuritySettingsRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_security_settings_flattened_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_settings), - '__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_security_settings( - 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_security_settings_flattened_error_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_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_security_settings( - security_settings.DeleteSecuritySettingsRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecuritySettingsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecuritySettingsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecuritySettingsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecuritySettingsServiceGrpcTransport, - transports.SecuritySettingsServiceGrpcAsyncIOTransport, -]) -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 = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecuritySettingsServiceGrpcTransport, - ) - -def test_security_settings_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecuritySettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_settings_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecuritySettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_security_settings', - 'get_security_settings', - 'update_security_settings', - 'list_security_settings', - 'delete_security_settings', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_security_settings_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecuritySettingsServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecuritySettingsServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_security_settings_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecuritySettingsServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_security_settings_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SecuritySettingsServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SecuritySettingsServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecuritySettingsServiceGrpcTransport, - transports.SecuritySettingsServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_security_settings_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecuritySettingsServiceGrpcTransport, - transports.SecuritySettingsServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), - (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_security_settings_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), - (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_security_settings_service_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), - (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_security_settings_service_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) -def test_security_settings_service_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_security_settings_service_host_no_port(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_security_settings_service_host_with_port(): - client = SecuritySettingsServiceClient( - 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_security_settings_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecuritySettingsServiceGrpcTransport( - 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_security_settings_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( - 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.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) -def test_security_settings_service_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.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) -def test_security_settings_service_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_security_settings_path(): - project = "squid" - location = "clam" - security_settings = "whelk" - expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - actual = SecuritySettingsServiceClient.security_settings_path(project, location, security_settings) - assert expected == actual - - -def test_parse_security_settings_path(): - expected = { - "project": "octopus", - "location": "oyster", - "security_settings": "nudibranch", - } - path = SecuritySettingsServiceClient.security_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.parse_security_settings_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecuritySettingsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SecuritySettingsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecuritySettingsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SecuritySettingsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecuritySettingsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SecuritySettingsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SecuritySettingsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SecuritySettingsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.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 = SecuritySettingsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SecuritySettingsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.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.SecuritySettingsServiceTransport, '_prep_wrapped_messages') as prep: - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecuritySettingsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SecuritySettingsServiceClient.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/v3/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py deleted file mode 100644 index 735e2642..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py +++ /dev/null @@ -1,2373 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.session_entity_types import SessionEntityTypesAsyncClient -from google.cloud.dialogflowcx_v3.services.session_entity_types import SessionEntityTypesClient -from google.cloud.dialogflowcx_v3.services.session_entity_types import pagers -from google.cloud.dialogflowcx_v3.services.session_entity_types import transports -from google.cloud.dialogflowcx_v3.services.session_entity_types.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.session_entity_types.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import entity_type -from google.cloud.dialogflowcx_v3.types import session_entity_type -from google.cloud.dialogflowcx_v3.types import session_entity_type as gcdc_session_entity_type -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3.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=gcdc_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 = gcdc_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - ) - response = client.create_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == 'name_value' - assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE - - -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] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() - - -@pytest.mark.asyncio -async def test_create_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - )) - response = await client.create_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == 'name_value' - assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE - - -@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_session_entity_type( - parent='parent_value', - session_entity_type=gcdc_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 == gcdc_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( - gcdc_session_entity_type.CreateSessionEntityTypeRequest(), - parent='parent_value', - session_entity_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( - gcdc_session_entity_type.CreateSessionEntityTypeRequest(), - parent='parent_value', - session_entity_type=gcdc_session_entity_type.SessionEntityType(name='name_value'), - ) - - -def test_update_session_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - ) - response = client.update_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == 'name_value' - assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE - - -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] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() - - -@pytest.mark.asyncio -async def test_update_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - )) - response = await client.update_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == 'name_value' - assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE - - -@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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() - - request.session_entity_type.name = 'session_entity_type.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_session_entity_type), - '__call__') as call: - call.return_value = gcdc_session_entity_type.SessionEntityType() - client.update_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() - - request.session_entity_type.name = 'session_entity_type.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_session_entity_type), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_session_entity_type.SessionEntityType()) - await client.update_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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 = gcdc_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_session_entity_type( - session_entity_type=gcdc_session_entity_type.SessionEntityType(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].session_entity_type == gcdc_session_entity_type.SessionEntityType(name='name_value') - assert args[0].update_mask == field_mask_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( - gcdc_session_entity_type.UpdateSessionEntityTypeRequest(), - session_entity_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( - gcdc_session_entity_type.UpdateSessionEntityTypeRequest(), - session_entity_type=gcdc_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.dialogflowcx_v3.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.dialogflowcx_v3.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - 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.dialogflowcx_v3.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" - location = "clam" - agent = "whelk" - session = "octopus" - entity_type = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, session=session, entity_type=entity_type, ) - actual = SessionEntityTypesClient.session_entity_type_path(project, location, agent, session, entity_type) - assert expected == actual - - -def test_parse_session_entity_type_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "session": "winkle", - "entity_type": "nautilus", - } - 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 = "scallop" - 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": "abalone", - } - 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 = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = SessionEntityTypesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - 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 = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SessionEntityTypesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - 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 = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = SessionEntityTypesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - 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": "winkle", - "location": "nautilus", - } - 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/v3/tests/unit/gapic/dialogflowcx_v3/test_sessions.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_sessions.py deleted file mode 100644 index f365628e..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_sessions.py +++ /dev/null @@ -1,1708 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.sessions import SessionsAsyncClient -from google.cloud.dialogflowcx_v3.services.sessions import SessionsClient -from google.cloud.dialogflowcx_v3.services.sessions import transports -from google.cloud.dialogflowcx_v3.services.sessions.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.sessions.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import audio_config -from google.cloud.dialogflowcx_v3.types import entity_type -from google.cloud.dialogflowcx_v3.types import intent -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import session -from google.cloud.dialogflowcx_v3.types import session_entity_type -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # 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.dialogflowcx_v3.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=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 = session.DetectIntentResponse( - response_id='response_id_value', - output_audio=b'output_audio_blob', - ) - response = client.detect_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == session.DetectIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.DetectIntentResponse) - assert response.response_id == 'response_id_value' - assert response.output_audio == b'output_audio_blob' - - -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] == session.DetectIntentRequest() - - -@pytest.mark.asyncio -async def test_detect_intent_async(transport: str = 'grpc_asyncio', request_type=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(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] == session.DetectIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.DetectIntentResponse) - assert response.response_id == 'response_id_value' - assert response.output_audio == b'output_audio_blob' - - -@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 = session.DetectIntentRequest() - - request.session = 'session/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detect_intent), - '__call__') as call: - call.return_value = session.DetectIntentResponse() - client.detect_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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 = 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(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_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_match_intent(transport: str = 'grpc', request_type=session.MatchIntentRequest): - 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.match_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = session.MatchIntentResponse( - text='text_value', - ) - response = client.match_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.MatchIntentResponse) - - -def test_match_intent_from_dict(): - test_match_intent(request_type=dict) - - -def test_match_intent_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.match_intent), - '__call__') as call: - client.match_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() - - -@pytest.mark.asyncio -async def test_match_intent_async(transport: str = 'grpc_asyncio', request_type=session.MatchIntentRequest): - 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.match_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session.MatchIntentResponse( - )) - response = await client.match_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.MatchIntentResponse) - - -@pytest.mark.asyncio -async def test_match_intent_async_from_dict(): - await test_match_intent_async(request_type=dict) - - -def test_match_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 = session.MatchIntentRequest() - - request.session = 'session/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.match_intent), - '__call__') as call: - call.return_value = session.MatchIntentResponse() - client.match_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_match_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 = session.MatchIntentRequest() - - request.session = 'session/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.match_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session.MatchIntentResponse()) - await client.match_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_fulfill_intent(transport: str = 'grpc', request_type=session.FulfillIntentRequest): - 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.fulfill_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = session.FulfillIntentResponse( - response_id='response_id_value', - output_audio=b'output_audio_blob', - ) - response = client.fulfill_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.FulfillIntentResponse) - assert response.response_id == 'response_id_value' - assert response.output_audio == b'output_audio_blob' - - -def test_fulfill_intent_from_dict(): - test_fulfill_intent(request_type=dict) - - -def test_fulfill_intent_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fulfill_intent), - '__call__') as call: - client.fulfill_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() - - -@pytest.mark.asyncio -async def test_fulfill_intent_async(transport: str = 'grpc_asyncio', request_type=session.FulfillIntentRequest): - 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.fulfill_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session.FulfillIntentResponse( - response_id='response_id_value', - output_audio=b'output_audio_blob', - )) - response = await client.fulfill_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.FulfillIntentResponse) - assert response.response_id == 'response_id_value' - assert response.output_audio == b'output_audio_blob' - - -@pytest.mark.asyncio -async def test_fulfill_intent_async_from_dict(): - await test_fulfill_intent_async(request_type=dict) - - -def test_fulfill_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 = session.FulfillIntentRequest() - - request.match_intent_request.session = 'match_intent_request.session/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fulfill_intent), - '__call__') as call: - call.return_value = session.FulfillIntentResponse() - client.fulfill_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'match_intent_request.session=match_intent_request.session/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_fulfill_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 = session.FulfillIntentRequest() - - request.match_intent_request.session = 'match_intent_request.session/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fulfill_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session.FulfillIntentResponse()) - await client.fulfill_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'match_intent_request.session=match_intent_request.session/value', - ) in kw['metadata'] - - -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.dialogflowcx_v3.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', - 'match_intent', - 'fulfill_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.dialogflowcx_v3.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_sessions_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (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.dialogflowcx_v3.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_entity_type_path(): - project = "squid" - location = "clam" - agent = "whelk" - entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - actual = SessionsClient.entity_type_path(project, location, agent, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "entity_type": "mussel", - } - path = SessionsClient.entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_entity_type_path(path) - assert expected == actual - -def test_flow_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = SessionsClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "flow": "octopus", - } - path = SessionsClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_flow_path(path) - assert expected == actual - -def test_intent_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = SessionsClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "intent": "abalone", - } - path = SessionsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_intent_path(path) - assert expected == actual - -def test_page_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - actual = SessionsClient.page_path(project, location, agent, flow, page) - assert expected == actual - - -def test_parse_page_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "flow": "winkle", - "page": "nautilus", - } - path = SessionsClient.page_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_page_path(path) - assert expected == actual - -def test_session_path(): - project = "scallop" - location = "abalone" - agent = "squid" - session = "clam" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format(project=project, location=location, agent=agent, session=session, ) - actual = SessionsClient.session_path(project, location, agent, session) - assert expected == actual - - -def test_parse_session_path(): - expected = { - "project": "whelk", - "location": "octopus", - "agent": "oyster", - "session": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - agent = "winkle" - session = "nautilus" - entity_type = "scallop" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, session=session, entity_type=entity_type, ) - actual = SessionsClient.session_entity_type_path(project, location, agent, session, entity_type) - assert expected == actual - - -def test_parse_session_entity_type_path(): - expected = { - "project": "abalone", - "location": "squid", - "agent": "clam", - "session": "whelk", - "entity_type": "octopus", - } - 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_transition_route_group_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - flow = "mussel" - transition_route_group = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - actual = SessionsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) - assert expected == actual - - -def test_parse_transition_route_group_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "agent": "abalone", - "flow": "squid", - "transition_route_group": "clam", - } - path = SessionsClient.transition_route_group_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_transition_route_group_path(path) - assert expected == actual - -def test_webhook_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - webhook = "nudibranch" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = SessionsClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "agent": "winkle", - "webhook": "nautilus", - } - path = SessionsClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - 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": "abalone", - } - 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 = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = SessionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - 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 = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SessionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - 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 = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = SessionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - 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": "winkle", - "location": "nautilus", - } - 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/v3/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py deleted file mode 100644 index 423c4fa3..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py +++ /dev/null @@ -1,4061 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.test_cases import TestCasesAsyncClient -from google.cloud.dialogflowcx_v3.services.test_cases import TestCasesClient -from google.cloud.dialogflowcx_v3.services.test_cases import pagers -from google.cloud.dialogflowcx_v3.services.test_cases import transports -from google.cloud.dialogflowcx_v3.services.test_cases.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.test_cases.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import audio_config -from google.cloud.dialogflowcx_v3.types import fulfillment -from google.cloud.dialogflowcx_v3.types import intent -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import response_message -from google.cloud.dialogflowcx_v3.types import session -from google.cloud.dialogflowcx_v3.types import test_case -from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 -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 struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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 TestCasesClient._get_default_mtls_endpoint(None) is None - assert TestCasesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TestCasesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TestCasesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TestCasesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TestCasesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - TestCasesClient, - TestCasesAsyncClient, -]) -def test_test_cases_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", [ - TestCasesClient, - TestCasesAsyncClient, -]) -def test_test_cases_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_test_cases_client_get_transport_class(): - transport = TestCasesClient.get_transport_class() - available_transports = [ - transports.TestCasesGrpcTransport, - ] - assert transport in available_transports - - transport = TestCasesClient.get_transport_class("grpc") - assert transport == transports.TestCasesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), - (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(TestCasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesClient)) -@mock.patch.object(TestCasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesAsyncClient)) -def test_test_cases_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(TestCasesClient, '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(TestCasesClient, '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", [ - (TestCasesClient, transports.TestCasesGrpcTransport, "grpc", "true"), - (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TestCasesClient, transports.TestCasesGrpcTransport, "grpc", "false"), - (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(TestCasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesClient)) -@mock.patch.object(TestCasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_test_cases_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", [ - (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), - (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_test_cases_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", [ - (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), - (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_test_cases_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_test_cases_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TestCasesClient( - 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_test_cases(transport: str = 'grpc', request_type=test_case.ListTestCasesRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCasesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCasesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_test_cases_from_dict(): - test_list_test_cases(request_type=dict) - - -def test_list_test_cases_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_cases), - '__call__') as call: - client.list_test_cases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() - - -@pytest.mark.asyncio -async def test_list_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ListTestCasesRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCasesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_test_cases_async_from_dict(): - await test_list_test_cases_async(request_type=dict) - - -def test_list_test_cases_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ListTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - call.return_value = test_case.ListTestCasesResponse() - client.list_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_cases_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ListTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse()) - await client.list_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_cases_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCasesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_test_cases( - parent='parent_value', - ) - - # Establish that the 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_test_cases_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_test_cases( - test_case.ListTestCasesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_test_cases_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCasesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_test_cases( - 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_test_cases_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_test_cases( - test_case.ListTestCasesRequest(), - parent='parent_value', - ) - - -def test_list_test_cases_pager(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - test_case.TestCase(), - ], - next_page_token='abc', - ), - test_case.ListTestCasesResponse( - test_cases=[], - next_page_token='def', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - ], - next_page_token='ghi', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_test_cases(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, test_case.TestCase) - for i in results) - -def test_list_test_cases_pages(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - test_case.TestCase(), - ], - next_page_token='abc', - ), - test_case.ListTestCasesResponse( - test_cases=[], - next_page_token='def', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - ], - next_page_token='ghi', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - ], - ), - RuntimeError, - ) - pages = list(client.list_test_cases(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_test_cases_async_pager(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - test_case.TestCase(), - ], - next_page_token='abc', - ), - test_case.ListTestCasesResponse( - test_cases=[], - next_page_token='def', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - ], - next_page_token='ghi', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_test_cases(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, test_case.TestCase) - for i in responses) - -@pytest.mark.asyncio -async def test_list_test_cases_async_pages(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - test_case.TestCase(), - ], - next_page_token='abc', - ), - test_case.ListTestCasesResponse( - test_cases=[], - next_page_token='def', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - ], - next_page_token='ghi', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_test_cases(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_batch_delete_test_cases(transport: str = 'grpc', request_type=test_case.BatchDeleteTestCasesRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.batch_delete_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_batch_delete_test_cases_from_dict(): - test_batch_delete_test_cases(request_type=dict) - - -def test_batch_delete_test_cases_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_cases), - '__call__') as call: - client.batch_delete_test_cases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() - - -@pytest.mark.asyncio -async def test_batch_delete_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.BatchDeleteTestCasesRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.batch_delete_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_batch_delete_test_cases_async_from_dict(): - await test_batch_delete_test_cases_async(request_type=dict) - - -def test_batch_delete_test_cases_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.BatchDeleteTestCasesRequest() - - 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_test_cases), - '__call__') as call: - call.return_value = None - client.batch_delete_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_cases_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.BatchDeleteTestCasesRequest() - - 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_test_cases), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.batch_delete_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_cases_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_test_cases), - '__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.batch_delete_test_cases( - 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_delete_test_cases_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_delete_test_cases( - test_case.BatchDeleteTestCasesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_batch_delete_test_cases_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_test_cases), - '__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.batch_delete_test_cases( - 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_delete_test_cases_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.batch_delete_test_cases( - test_case.BatchDeleteTestCasesRequest(), - parent='parent_value', - ) - - -def test_get_test_case(transport: str = 'grpc', request_type=test_case.GetTestCaseRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - ) - response = client.get_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -def test_get_test_case_from_dict(): - test_get_test_case(request_type=dict) - - -def test_get_test_case_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - client.get_test_case() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() - - -@pytest.mark.asyncio -async def test_get_test_case_async(transport: str = 'grpc_asyncio', request_type=test_case.GetTestCaseRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - )) - response = await client.get_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -@pytest.mark.asyncio -async def test_get_test_case_async_from_dict(): - await test_get_test_case_async(request_type=dict) - - -def test_get_test_case_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.GetTestCaseRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - call.return_value = test_case.TestCase() - client.get_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_test_case_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.GetTestCaseRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase()) - await client.get_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_test_case_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCase() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_test_case( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_test_case_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_test_case( - test_case.GetTestCaseRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_test_case_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_test_case( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_test_case_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_test_case( - test_case.GetTestCaseRequest(), - name='name_value', - ) - - -def test_create_test_case(transport: str = 'grpc', request_type=gcdc_test_case.CreateTestCaseRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - ) - response = client.create_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -def test_create_test_case_from_dict(): - test_create_test_case(request_type=dict) - - -def test_create_test_case_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_case), - '__call__') as call: - client.create_test_case() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() - - -@pytest.mark.asyncio -async def test_create_test_case_async(transport: str = 'grpc_asyncio', request_type=gcdc_test_case.CreateTestCaseRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - )) - response = await client.create_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -@pytest.mark.asyncio -async def test_create_test_case_async_from_dict(): - await test_create_test_case_async(request_type=dict) - - -def test_create_test_case_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_test_case.CreateTestCaseRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - call.return_value = gcdc_test_case.TestCase() - client.create_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_case_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_test_case.CreateTestCaseRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) - await client.create_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_case_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_test_case( - parent='parent_value', - test_case=gcdc_test_case.TestCase(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].test_case == gcdc_test_case.TestCase(name='name_value') - - -def test_create_test_case_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_test_case( - gcdc_test_case.CreateTestCaseRequest(), - parent='parent_value', - test_case=gcdc_test_case.TestCase(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_test_case_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_test_case( - parent='parent_value', - test_case=gcdc_test_case.TestCase(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].test_case == gcdc_test_case.TestCase(name='name_value') - - -@pytest.mark.asyncio -async def test_create_test_case_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_test_case( - gcdc_test_case.CreateTestCaseRequest(), - parent='parent_value', - test_case=gcdc_test_case.TestCase(name='name_value'), - ) - - -def test_update_test_case(transport: str = 'grpc', request_type=gcdc_test_case.UpdateTestCaseRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - ) - response = client.update_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -def test_update_test_case_from_dict(): - test_update_test_case(request_type=dict) - - -def test_update_test_case_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_case), - '__call__') as call: - client.update_test_case() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() - - -@pytest.mark.asyncio -async def test_update_test_case_async(transport: str = 'grpc_asyncio', request_type=gcdc_test_case.UpdateTestCaseRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - )) - response = await client.update_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -@pytest.mark.asyncio -async def test_update_test_case_async_from_dict(): - await test_update_test_case_async(request_type=dict) - - -def test_update_test_case_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_test_case.UpdateTestCaseRequest() - - request.test_case.name = 'test_case.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - call.return_value = gcdc_test_case.TestCase() - client.update_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'test_case.name=test_case.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_test_case_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_test_case.UpdateTestCaseRequest() - - request.test_case.name = 'test_case.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) - await client.update_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'test_case.name=test_case.name/value', - ) in kw['metadata'] - - -def test_update_test_case_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_test_case( - test_case=gcdc_test_case.TestCase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].test_case == gcdc_test_case.TestCase(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_test_case_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_test_case( - gcdc_test_case.UpdateTestCaseRequest(), - test_case=gcdc_test_case.TestCase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_test_case_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_test_case( - test_case=gcdc_test_case.TestCase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].test_case == gcdc_test_case.TestCase(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_test_case_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_test_case( - gcdc_test_case.UpdateTestCaseRequest(), - test_case=gcdc_test_case.TestCase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_run_test_case(transport: str = 'grpc', request_type=test_case.RunTestCaseRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_test_case_from_dict(): - test_run_test_case(request_type=dict) - - -def test_run_test_case_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_test_case), - '__call__') as call: - client.run_test_case() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() - - -@pytest.mark.asyncio -async def test_run_test_case_async(transport: str = 'grpc_asyncio', request_type=test_case.RunTestCaseRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_test_case), - '__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.run_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_run_test_case_async_from_dict(): - await test_run_test_case_async(request_type=dict) - - -def test_run_test_case_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.RunTestCaseRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_test_case), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_run_test_case_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.RunTestCaseRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_test_case), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_batch_run_test_cases(transport: str = 'grpc', request_type=test_case.BatchRunTestCasesRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.batch_run_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_batch_run_test_cases_from_dict(): - test_batch_run_test_cases(request_type=dict) - - -def test_batch_run_test_cases_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_run_test_cases), - '__call__') as call: - client.batch_run_test_cases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() - - -@pytest.mark.asyncio -async def test_batch_run_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.BatchRunTestCasesRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_test_cases), - '__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_run_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_run_test_cases_async_from_dict(): - await test_batch_run_test_cases_async(request_type=dict) - - -def test_batch_run_test_cases_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.BatchRunTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_test_cases), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.batch_run_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_run_test_cases_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.BatchRunTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_test_cases), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.batch_run_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_calculate_coverage(transport: str = 'grpc', request_type=test_case.CalculateCoverageRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.calculate_coverage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.CalculateCoverageResponse( - agent='agent_value', - intent_coverage=test_case.IntentCoverage(intents=[test_case.IntentCoverage.Intent(intent='intent_value')]), - ) - response = client.calculate_coverage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.CalculateCoverageResponse) - assert response.agent == 'agent_value' - - -def test_calculate_coverage_from_dict(): - test_calculate_coverage(request_type=dict) - - -def test_calculate_coverage_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.calculate_coverage), - '__call__') as call: - client.calculate_coverage() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() - - -@pytest.mark.asyncio -async def test_calculate_coverage_async(transport: str = 'grpc_asyncio', request_type=test_case.CalculateCoverageRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.calculate_coverage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.CalculateCoverageResponse( - agent='agent_value', - )) - response = await client.calculate_coverage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.CalculateCoverageResponse) - assert response.agent == 'agent_value' - - -@pytest.mark.asyncio -async def test_calculate_coverage_async_from_dict(): - await test_calculate_coverage_async(request_type=dict) - - -def test_calculate_coverage_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.CalculateCoverageRequest() - - request.agent = 'agent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.calculate_coverage), - '__call__') as call: - call.return_value = test_case.CalculateCoverageResponse() - client.calculate_coverage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=agent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_calculate_coverage_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.CalculateCoverageRequest() - - request.agent = 'agent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.calculate_coverage), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.CalculateCoverageResponse()) - await client.calculate_coverage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'agent=agent/value', - ) in kw['metadata'] - - -def test_import_test_cases(transport: str = 'grpc', request_type=test_case.ImportTestCasesRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_test_cases_from_dict(): - test_import_test_cases(request_type=dict) - - -def test_import_test_cases_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_cases), - '__call__') as call: - client.import_test_cases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() - - -@pytest.mark.asyncio -async def test_import_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ImportTestCasesRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_test_cases), - '__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_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_test_cases_async_from_dict(): - await test_import_test_cases_async(request_type=dict) - - -def test_import_test_cases_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ImportTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_test_cases), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_cases_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ImportTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_test_cases), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_cases(transport: str = 'grpc', request_type=test_case.ExportTestCasesRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.export_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_export_test_cases_from_dict(): - test_export_test_cases(request_type=dict) - - -def test_export_test_cases_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_cases), - '__call__') as call: - client.export_test_cases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() - - -@pytest.mark.asyncio -async def test_export_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ExportTestCasesRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_test_cases), - '__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_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_test_cases_async_from_dict(): - await test_export_test_cases_async(request_type=dict) - - -def test_export_test_cases_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ExportTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_test_cases), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_cases_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ExportTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_test_cases), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.export_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_case_results(transport: str = 'grpc', request_type=test_case.ListTestCaseResultsRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCaseResultsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_test_case_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCaseResultsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_test_case_results_from_dict(): - test_list_test_case_results(request_type=dict) - - -def test_list_test_case_results_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_case_results), - '__call__') as call: - client.list_test_case_results() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() - - -@pytest.mark.asyncio -async def test_list_test_case_results_async(transport: str = 'grpc_asyncio', request_type=test_case.ListTestCaseResultsRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_test_case_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCaseResultsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_test_case_results_async_from_dict(): - await test_list_test_case_results_async(request_type=dict) - - -def test_list_test_case_results_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ListTestCaseResultsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - call.return_value = test_case.ListTestCaseResultsResponse() - client.list_test_case_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_case_results_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ListTestCaseResultsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse()) - await client.list_test_case_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_case_results_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCaseResultsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_test_case_results( - parent='parent_value', - ) - - # Establish that the 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_test_case_results_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_test_case_results( - test_case.ListTestCaseResultsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_test_case_results_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCaseResultsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_test_case_results( - 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_test_case_results_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_test_case_results( - test_case.ListTestCaseResultsRequest(), - parent='parent_value', - ) - - -def test_list_test_case_results_pager(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - next_page_token='abc', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[], - next_page_token='def', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - ], - next_page_token='ghi', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_test_case_results(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, test_case.TestCaseResult) - for i in results) - -def test_list_test_case_results_pages(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - next_page_token='abc', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[], - next_page_token='def', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - ], - next_page_token='ghi', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_test_case_results(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_test_case_results_async_pager(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - next_page_token='abc', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[], - next_page_token='def', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - ], - next_page_token='ghi', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_test_case_results(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, test_case.TestCaseResult) - for i in responses) - -@pytest.mark.asyncio -async def test_list_test_case_results_async_pages(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - next_page_token='abc', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[], - next_page_token='def', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - ], - next_page_token='ghi', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_test_case_results(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_test_case_result(transport: str = 'grpc', request_type=test_case.GetTestCaseResultRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCaseResult( - name='name_value', - environment='environment_value', - test_result=test_case.TestResult.PASSED, - ) - response = client.get_test_case_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.TestCaseResult) - assert response.name == 'name_value' - assert response.environment == 'environment_value' - assert response.test_result == test_case.TestResult.PASSED - - -def test_get_test_case_result_from_dict(): - test_get_test_case_result(request_type=dict) - - -def test_get_test_case_result_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - client.get_test_case_result() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseResultRequest() - - -@pytest.mark.asyncio -async def test_get_test_case_result_async(transport: str = 'grpc_asyncio', request_type=test_case.GetTestCaseResultRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult( - name='name_value', - environment='environment_value', - test_result=test_case.TestResult.PASSED, - )) - response = await client.get_test_case_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.TestCaseResult) - assert response.name == 'name_value' - assert response.environment == 'environment_value' - assert response.test_result == test_case.TestResult.PASSED - - -@pytest.mark.asyncio -async def test_get_test_case_result_async_from_dict(): - await test_get_test_case_result_async(request_type=dict) - - -def test_get_test_case_result_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.GetTestCaseResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - call.return_value = test_case.TestCaseResult() - client.get_test_case_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_test_case_result_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.GetTestCaseResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult()) - await client.get_test_case_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_test_case_result_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCaseResult() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_test_case_result( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_test_case_result_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_test_case_result( - test_case.GetTestCaseResultRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_test_case_result_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCaseResult() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_test_case_result( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_test_case_result_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_test_case_result( - test_case.GetTestCaseResultRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TestCasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TestCasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TestCasesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TestCasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TestCasesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TestCasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TestCasesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TestCasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TestCasesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TestCasesGrpcTransport, - transports.TestCasesGrpcAsyncIOTransport, -]) -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 = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TestCasesGrpcTransport, - ) - -def test_test_cases_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TestCasesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_test_cases_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TestCasesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_test_cases', - 'batch_delete_test_cases', - 'get_test_case', - 'create_test_case', - 'update_test_case', - 'run_test_case', - 'batch_run_test_cases', - 'calculate_coverage', - 'import_test_cases', - 'export_test_cases', - 'list_test_case_results', - 'get_test_case_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_test_cases_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TestCasesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_test_cases_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TestCasesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_test_cases_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TestCasesTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_test_cases_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - TestCasesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_test_cases_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - TestCasesClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TestCasesGrpcTransport, - transports.TestCasesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_test_cases_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TestCasesGrpcTransport, - transports.TestCasesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_test_cases_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TestCasesGrpcTransport, grpc_helpers), - (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_test_cases_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TestCasesGrpcTransport, grpc_helpers), - (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_test_cases_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TestCasesGrpcTransport, grpc_helpers), - (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_test_cases_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) -def test_test_cases_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = 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_test_cases_host_no_port(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_test_cases_host_with_port(): - client = TestCasesClient( - 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_test_cases_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TestCasesGrpcTransport( - 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_test_cases_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TestCasesGrpcAsyncIOTransport( - 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.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) -def test_test_cases_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.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) -def test_test_cases_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_test_cases_grpc_lro_client(): - client = TestCasesClient( - 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_test_cases_grpc_lro_async_client(): - client = TestCasesAsyncClient( - 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" - location = "clam" - agent = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) - actual = TestCasesClient.agent_path(project, location, agent) - assert expected == actual - - -def test_parse_agent_path(): - expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - } - path = TestCasesClient.agent_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_agent_path(path) - assert expected == actual - -def test_entity_type_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - entity_type = "nautilus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - actual = TestCasesClient.entity_type_path(project, location, agent, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "scallop", - "location": "abalone", - "agent": "squid", - "entity_type": "clam", - } - path = TestCasesClient.entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_entity_type_path(path) - assert expected == actual - -def test_environment_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - environment = "nudibranch" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - actual = TestCasesClient.environment_path(project, location, agent, environment) - assert expected == actual - - -def test_parse_environment_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "agent": "winkle", - "environment": "nautilus", - } - path = TestCasesClient.environment_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_environment_path(path) - assert expected == actual - -def test_flow_path(): - project = "scallop" - location = "abalone" - agent = "squid" - flow = "clam" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = TestCasesClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "whelk", - "location": "octopus", - "agent": "oyster", - "flow": "nudibranch", - } - path = TestCasesClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_flow_path(path) - assert expected == actual - -def test_intent_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - intent = "nautilus" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = TestCasesClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "scallop", - "location": "abalone", - "agent": "squid", - "intent": "clam", - } - path = TestCasesClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_intent_path(path) - assert expected == actual - -def test_page_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - flow = "nudibranch" - page = "cuttlefish" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - actual = TestCasesClient.page_path(project, location, agent, flow, page) - assert expected == actual - - -def test_parse_page_path(): - expected = { - "project": "mussel", - "location": "winkle", - "agent": "nautilus", - "flow": "scallop", - "page": "abalone", - } - path = TestCasesClient.page_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_page_path(path) - assert expected == actual - -def test_test_case_path(): - project = "squid" - location = "clam" - agent = "whelk" - test_case = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(project=project, location=location, agent=agent, test_case=test_case, ) - actual = TestCasesClient.test_case_path(project, location, agent, test_case) - assert expected == actual - - -def test_parse_test_case_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "test_case": "mussel", - } - path = TestCasesClient.test_case_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_test_case_path(path) - assert expected == actual - -def test_test_case_result_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - test_case = "abalone" - result = "squid" - expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) - actual = TestCasesClient.test_case_result_path(project, location, agent, test_case, result) - assert expected == actual - - -def test_parse_test_case_result_path(): - expected = { - "project": "clam", - "location": "whelk", - "agent": "octopus", - "test_case": "oyster", - "result": "nudibranch", - } - path = TestCasesClient.test_case_result_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_test_case_result_path(path) - assert expected == actual - -def test_transition_route_group_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - flow = "nautilus" - transition_route_group = "scallop" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - actual = TestCasesClient.transition_route_group_path(project, location, agent, flow, transition_route_group) - assert expected == actual - - -def test_parse_transition_route_group_path(): - expected = { - "project": "abalone", - "location": "squid", - "agent": "clam", - "flow": "whelk", - "transition_route_group": "octopus", - } - path = TestCasesClient.transition_route_group_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_transition_route_group_path(path) - assert expected == actual - -def test_webhook_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - webhook = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = TestCasesClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "webhook": "abalone", - } - path = TestCasesClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TestCasesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = TestCasesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = TestCasesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = TestCasesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TestCasesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = TestCasesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = TestCasesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = TestCasesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = TestCasesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = TestCasesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.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.TestCasesTransport, '_prep_wrapped_messages') as prep: - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TestCasesTransport, '_prep_wrapped_messages') as prep: - transport_class = TestCasesClient.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/v3/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py deleted file mode 100644 index 3f30ccc2..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py +++ /dev/null @@ -1,2470 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.transition_route_groups import TransitionRouteGroupsAsyncClient -from google.cloud.dialogflowcx_v3.services.transition_route_groups import TransitionRouteGroupsClient -from google.cloud.dialogflowcx_v3.services.transition_route_groups import pagers -from google.cloud.dialogflowcx_v3.services.transition_route_groups import transports -from google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import fulfillment -from google.cloud.dialogflowcx_v3.types import page -from google.cloud.dialogflowcx_v3.types import response_message -from google.cloud.dialogflowcx_v3.types import transition_route_group -from google.cloud.dialogflowcx_v3.types import transition_route_group as gcdc_transition_route_group -from google.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 TransitionRouteGroupsClient._get_default_mtls_endpoint(None) is None - assert TransitionRouteGroupsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TransitionRouteGroupsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TransitionRouteGroupsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TransitionRouteGroupsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TransitionRouteGroupsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - TransitionRouteGroupsClient, - TransitionRouteGroupsAsyncClient, -]) -def test_transition_route_groups_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", [ - TransitionRouteGroupsClient, - TransitionRouteGroupsAsyncClient, -]) -def test_transition_route_groups_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_transition_route_groups_client_get_transport_class(): - transport = TransitionRouteGroupsClient.get_transport_class() - available_transports = [ - transports.TransitionRouteGroupsGrpcTransport, - ] - assert transport in available_transports - - transport = TransitionRouteGroupsClient.get_transport_class("grpc") - assert transport == transports.TransitionRouteGroupsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), - (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(TransitionRouteGroupsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsClient)) -@mock.patch.object(TransitionRouteGroupsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsAsyncClient)) -def test_transition_route_groups_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(TransitionRouteGroupsClient, '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(TransitionRouteGroupsClient, '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", [ - (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc", "true"), - (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc", "false"), - (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(TransitionRouteGroupsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsClient)) -@mock.patch.object(TransitionRouteGroupsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_transition_route_groups_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", [ - (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), - (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_transition_route_groups_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", [ - (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), - (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_transition_route_groups_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_transition_route_groups_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TransitionRouteGroupsClient( - 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_transition_route_groups(transport: str = 'grpc', request_type=transition_route_group.ListTransitionRouteGroupsRequest): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.ListTransitionRouteGroupsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_transition_route_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransitionRouteGroupsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_transition_route_groups_from_dict(): - test_list_transition_route_groups(request_type=dict) - - -def test_list_transition_route_groups_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TransitionRouteGroupsClient( - credentials=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_transition_route_groups), - '__call__') as call: - client.list_transition_route_groups() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() - - -@pytest.mark.asyncio -async def test_list_transition_route_groups_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.ListTransitionRouteGroupsRequest): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_transition_route_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransitionRouteGroupsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_transition_route_groups_async_from_dict(): - await test_list_transition_route_groups_async(request_type=dict) - - -def test_list_transition_route_groups_field_headers(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.ListTransitionRouteGroupsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() - client.list_transition_route_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_transition_route_groups_field_headers_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.ListTransitionRouteGroupsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse()) - await client.list_transition_route_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_transition_route_groups_flattened(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_transition_route_groups( - parent='parent_value', - ) - - # Establish that the 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_transition_route_groups_flattened_error(): - client = TransitionRouteGroupsClient( - credentials=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_transition_route_groups( - transition_route_group.ListTransitionRouteGroupsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_transition_route_groups_flattened_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_transition_route_groups( - 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_transition_route_groups_flattened_error_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_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_transition_route_groups( - transition_route_group.ListTransitionRouteGroupsRequest(), - parent='parent_value', - ) - - -def test_list_transition_route_groups_pager(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='abc', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[], - next_page_token='def', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='ghi', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_transition_route_groups(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, transition_route_group.TransitionRouteGroup) - for i in results) - -def test_list_transition_route_groups_pages(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='abc', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[], - next_page_token='def', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='ghi', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - ), - RuntimeError, - ) - pages = list(client.list_transition_route_groups(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_transition_route_groups_async_pager(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='abc', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[], - next_page_token='def', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='ghi', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_transition_route_groups(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, transition_route_group.TransitionRouteGroup) - for i in responses) - -@pytest.mark.asyncio -async def test_list_transition_route_groups_async_pages(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='abc', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[], - next_page_token='def', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='ghi', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_transition_route_groups(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_transition_route_group(transport: str = 'grpc', request_type=transition_route_group.GetTransitionRouteGroupRequest): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - ) - response = client.get_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_get_transition_route_group_from_dict(): - test_get_transition_route_group(request_type=dict) - - -def test_get_transition_route_group_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group), - '__call__') as call: - client.get_transition_route_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() - - -@pytest.mark.asyncio -async def test_get_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.GetTransitionRouteGroupRequest): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - )) - response = await client.get_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_get_transition_route_group_async_from_dict(): - await test_get_transition_route_group_async(request_type=dict) - - -def test_get_transition_route_group_field_headers(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.GetTransitionRouteGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transition_route_group), - '__call__') as call: - call.return_value = transition_route_group.TransitionRouteGroup() - client.get_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_transition_route_group_field_headers_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.GetTransitionRouteGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transition_route_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup()) - await client.get_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_transition_route_group_flattened(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_transition_route_group( - name='name_value', - ) - - # Establish that the 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_transition_route_group_flattened_error(): - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group( - transition_route_group.GetTransitionRouteGroupRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_transition_route_group_flattened_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.TransitionRouteGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_transition_route_group( - 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_transition_route_group_flattened_error_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_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_transition_route_group( - transition_route_group.GetTransitionRouteGroupRequest(), - name='name_value', - ) - - -def test_create_transition_route_group(transport: str = 'grpc', request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - ) - response = client.create_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_create_transition_route_group_from_dict(): - test_create_transition_route_group(request_type=dict) - - -def test_create_transition_route_group_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group), - '__call__') as call: - client.create_transition_route_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() - - -@pytest.mark.asyncio -async def test_create_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - )) - response = await client.create_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_create_transition_route_group_async_from_dict(): - await test_create_transition_route_group_async(request_type=dict) - - -def test_create_transition_route_group_field_headers(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transition_route_group), - '__call__') as call: - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - client.create_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_transition_route_group_field_headers_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transition_route_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) - await client.create_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_transition_route_group_flattened(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_transition_route_group( - parent='parent_value', - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') - - -def test_create_transition_route_group_flattened_error(): - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group( - gcdc_transition_route_group.CreateTransitionRouteGroupRequest(), - parent='parent_value', - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_transition_route_group_flattened_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_transition_route_group( - parent='parent_value', - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') - - -@pytest.mark.asyncio -async def test_create_transition_route_group_flattened_error_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_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_transition_route_group( - gcdc_transition_route_group.CreateTransitionRouteGroupRequest(), - parent='parent_value', - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), - ) - - -def test_update_transition_route_group(transport: str = 'grpc', request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - ) - response = client.update_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_transition_route_group_from_dict(): - test_update_transition_route_group(request_type=dict) - - -def test_update_transition_route_group_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group), - '__call__') as call: - client.update_transition_route_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() - - -@pytest.mark.asyncio -async def test_update_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_transition_route_group_async_from_dict(): - await test_update_transition_route_group_async(request_type=dict) - - -def test_update_transition_route_group_field_headers(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() - - request.transition_route_group.name = 'transition_route_group.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transition_route_group), - '__call__') as call: - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - client.update_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'transition_route_group.name=transition_route_group.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_transition_route_group_field_headers_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() - - request.transition_route_group.name = 'transition_route_group.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transition_route_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) - await client.update_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'transition_route_group.name=transition_route_group.name/value', - ) in kw['metadata'] - - -def test_update_transition_route_group_flattened(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_transition_route_group( - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_transition_route_group_flattened_error(): - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group( - gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(), - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_transition_route_group_flattened_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_transition_route_group( - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_transition_route_group_flattened_error_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_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_transition_route_group( - gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(), - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_transition_route_group(transport: str = 'grpc', request_type=transition_route_group.DeleteTransitionRouteGroupRequest): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_transition_route_group_from_dict(): - test_delete_transition_route_group(request_type=dict) - - -def test_delete_transition_route_group_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group), - '__call__') as call: - client.delete_transition_route_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() - - -@pytest.mark.asyncio -async def test_delete_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.DeleteTransitionRouteGroupRequest): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_transition_route_group_async_from_dict(): - await test_delete_transition_route_group_async(request_type=dict) - - -def test_delete_transition_route_group_field_headers(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.DeleteTransitionRouteGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transition_route_group), - '__call__') as call: - call.return_value = None - client.delete_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_transition_route_group_field_headers_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.DeleteTransitionRouteGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transition_route_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_transition_route_group_flattened(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transition_route_group), - '__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_transition_route_group( - 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_transition_route_group_flattened_error(): - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group( - transition_route_group.DeleteTransitionRouteGroupRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_transition_route_group_flattened_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transition_route_group), - '__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_transition_route_group( - 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_transition_route_group_flattened_error_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_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_transition_route_group( - transition_route_group.DeleteTransitionRouteGroupRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TransitionRouteGroupsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TransitionRouteGroupsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TransitionRouteGroupsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TransitionRouteGroupsGrpcTransport, - transports.TransitionRouteGroupsGrpcAsyncIOTransport, -]) -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 = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TransitionRouteGroupsGrpcTransport, - ) - -def test_transition_route_groups_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TransitionRouteGroupsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_transition_route_groups_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TransitionRouteGroupsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_transition_route_groups', - 'get_transition_route_group', - 'create_transition_route_group', - 'update_transition_route_group', - 'delete_transition_route_group', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_transition_route_groups_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TransitionRouteGroupsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TransitionRouteGroupsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_transition_route_groups_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TransitionRouteGroupsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_transition_route_groups_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - TransitionRouteGroupsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - TransitionRouteGroupsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TransitionRouteGroupsGrpcTransport, - transports.TransitionRouteGroupsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_transition_route_groups_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TransitionRouteGroupsGrpcTransport, - transports.TransitionRouteGroupsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), - (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_transition_route_groups_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), - (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_transition_route_groups_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), - (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_transition_route_groups_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) -def test_transition_route_groups_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_transition_route_groups_host_no_port(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_transition_route_groups_host_with_port(): - client = TransitionRouteGroupsClient( - 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_transition_route_groups_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TransitionRouteGroupsGrpcTransport( - 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_transition_route_groups_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport( - 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.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) -def test_transition_route_groups_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.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) -def test_transition_route_groups_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_flow_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = TransitionRouteGroupsClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "flow": "mussel", - } - path = TransitionRouteGroupsClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_flow_path(path) - assert expected == actual - -def test_intent_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - intent = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = TransitionRouteGroupsClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "intent": "octopus", - } - path = TransitionRouteGroupsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_intent_path(path) - assert expected == actual - -def test_page_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - flow = "mussel" - page = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - actual = TransitionRouteGroupsClient.page_path(project, location, agent, flow, page) - assert expected == actual - - -def test_parse_page_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "agent": "abalone", - "flow": "squid", - "page": "clam", - } - path = TransitionRouteGroupsClient.page_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_page_path(path) - assert expected == actual - -def test_transition_route_group_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - flow = "nudibranch" - transition_route_group = "cuttlefish" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - actual = TransitionRouteGroupsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) - assert expected == actual - - -def test_parse_transition_route_group_path(): - expected = { - "project": "mussel", - "location": "winkle", - "agent": "nautilus", - "flow": "scallop", - "transition_route_group": "abalone", - } - path = TransitionRouteGroupsClient.transition_route_group_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_transition_route_group_path(path) - assert expected == actual - -def test_webhook_path(): - project = "squid" - location = "clam" - agent = "whelk" - webhook = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = TransitionRouteGroupsClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "webhook": "mussel", - } - path = TransitionRouteGroupsClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TransitionRouteGroupsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = TransitionRouteGroupsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = TransitionRouteGroupsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = TransitionRouteGroupsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TransitionRouteGroupsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = TransitionRouteGroupsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = TransitionRouteGroupsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = TransitionRouteGroupsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.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 = TransitionRouteGroupsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = TransitionRouteGroupsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.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.TransitionRouteGroupsTransport, '_prep_wrapped_messages') as prep: - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TransitionRouteGroupsTransport, '_prep_wrapped_messages') as prep: - transport_class = TransitionRouteGroupsClient.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/v3/tests/unit/gapic/dialogflowcx_v3/test_versions.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_versions.py deleted file mode 100644 index c523b41d..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_versions.py +++ /dev/null @@ -1,2658 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.versions import VersionsAsyncClient -from google.cloud.dialogflowcx_v3.services.versions import VersionsClient -from google.cloud.dialogflowcx_v3.services.versions import pagers -from google.cloud.dialogflowcx_v3.services.versions import transports -from google.cloud.dialogflowcx_v3.services.versions.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.versions.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import flow -from google.cloud.dialogflowcx_v3.types import version -from google.cloud.dialogflowcx_v3.types import version as gcdc_version -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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(): - 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.dialogflowcx_v3.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', - display_name='display_name_value', - description='description_value', - state=version.Version.State.RUNNING, - ) - response = client.get_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == version.GetVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, version.Version) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == version.Version.State.RUNNING - - -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', - display_name='display_name_value', - description='description_value', - state=version.Version.State.RUNNING, - )) - response = await client.get_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == version.GetVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, version.Version) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == version.Version.State.RUNNING - - -@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=gcdc_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 = operations_pb2.Operation(name='operations/spam') - response = client.create_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.CreateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -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] == gcdc_version.CreateVersionRequest() - - -@pytest.mark.asyncio -async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.CreateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@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 = gcdc_version.CreateVersionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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 = gcdc_version.CreateVersionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - 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 = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_version( - parent='parent_value', - version=gcdc_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 == gcdc_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( - gcdc_version.CreateVersionRequest(), - parent='parent_value', - version=gcdc_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 = 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_version( - parent='parent_value', - version=gcdc_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 == gcdc_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( - gcdc_version.CreateVersionRequest(), - parent='parent_value', - version=gcdc_version.Version(name='name_value'), - ) - - -def test_update_version(transport: str = 'grpc', request_type=gcdc_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 = gcdc_version.Version( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_version.Version.State.RUNNING, - ) - response = client.update_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.UpdateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_version.Version) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_version.Version.State.RUNNING - - -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] == gcdc_version.UpdateVersionRequest() - - -@pytest.mark.asyncio -async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_version.Version( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_version.Version.State.RUNNING, - )) - response = await client.update_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.UpdateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_version.Version) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_version.Version.State.RUNNING - - -@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 = gcdc_version.UpdateVersionRequest() - - request.version.name = 'version.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: - call.return_value = gcdc_version.Version() - client.update_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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 = gcdc_version.UpdateVersionRequest() - - request.version.name = 'version.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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 = gcdc_version.Version() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_version( - version=gcdc_version.Version(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].version == gcdc_version.Version(name='name_value') - assert args[0].update_mask == field_mask_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( - gcdc_version.UpdateVersionRequest(), - version=gcdc_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 = gcdc_version.Version() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( - gcdc_version.UpdateVersionRequest(), - version=gcdc_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_load_version(transport: str = 'grpc', request_type=version.LoadVersionRequest): - 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.load_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.load_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == version.LoadVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_load_version_from_dict(): - test_load_version(request_type=dict) - - -def test_load_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_version), - '__call__') as call: - client.load_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == version.LoadVersionRequest() - - -@pytest.mark.asyncio -async def test_load_version_async(transport: str = 'grpc_asyncio', request_type=version.LoadVersionRequest): - 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.load_version), - '__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.load_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == version.LoadVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_load_version_async_from_dict(): - await test_load_version_async(request_type=dict) - - -def test_load_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.LoadVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.load_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_load_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.LoadVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.load_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_load_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.load_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.load_version( - name='name_value', - ) - - # Establish that the 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_load_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.load_version( - version.LoadVersionRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_load_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.load_version), - '__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.load_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_load_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.load_version( - version.LoadVersionRequest(), - 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.dialogflowcx_v3.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', - 'load_version', - ) - 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_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.dialogflowcx_v3.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VersionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_versions_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VersionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - 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.dialogflowcx_v3.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_versions_grpc_lro_client(): - client = VersionsClient( - 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_versions_grpc_lro_async_client(): - client = VersionsAsyncClient( - 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_version_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - version = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - actual = VersionsClient.version_path(project, location, agent, flow, version) - assert expected == actual - - -def test_parse_version_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "flow": "winkle", - "version": "nautilus", - } - 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 = "scallop" - 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": "abalone", - } - 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 = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = VersionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - 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 = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = VersionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - 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 = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = VersionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - 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": "winkle", - "location": "nautilus", - } - 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/v3/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py b/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py deleted file mode 100644 index d46cba9b..00000000 --- a/owl-bot-staging/v3/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py +++ /dev/null @@ -1,2409 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3.services.webhooks import WebhooksAsyncClient -from google.cloud.dialogflowcx_v3.services.webhooks import WebhooksClient -from google.cloud.dialogflowcx_v3.services.webhooks import pagers -from google.cloud.dialogflowcx_v3.services.webhooks import transports -from google.cloud.dialogflowcx_v3.services.webhooks.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3.services.webhooks.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3.types import webhook -from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # 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(): - 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 WebhooksClient._get_default_mtls_endpoint(None) is None - assert WebhooksClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WebhooksClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WebhooksClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WebhooksClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WebhooksClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - WebhooksClient, - WebhooksAsyncClient, -]) -def test_webhooks_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", [ - WebhooksClient, - WebhooksAsyncClient, -]) -def test_webhooks_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_webhooks_client_get_transport_class(): - transport = WebhooksClient.get_transport_class() - available_transports = [ - transports.WebhooksGrpcTransport, - ] - assert transport in available_transports - - transport = WebhooksClient.get_transport_class("grpc") - assert transport == transports.WebhooksGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), - (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(WebhooksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksClient)) -@mock.patch.object(WebhooksAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksAsyncClient)) -def test_webhooks_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(WebhooksClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=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(WebhooksClient, '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", [ - (WebhooksClient, transports.WebhooksGrpcTransport, "grpc", "true"), - (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WebhooksClient, transports.WebhooksGrpcTransport, "grpc", "false"), - (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(WebhooksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksClient)) -@mock.patch.object(WebhooksAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_webhooks_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", [ - (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), - (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_webhooks_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", [ - (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), - (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_webhooks_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_webhooks_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WebhooksClient( - 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_webhooks(transport: str = 'grpc', request_type=webhook.ListWebhooksRequest): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhooks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.ListWebhooksResponse( - next_page_token='next_page_token_value', - ) - response = client.list_webhooks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWebhooksPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_webhooks_from_dict(): - test_list_webhooks(request_type=dict) - - -def test_list_webhooks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebhooksClient( - credentials=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_webhooks), - '__call__') as call: - client.list_webhooks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() - - -@pytest.mark.asyncio -async def test_list_webhooks_async(transport: str = 'grpc_asyncio', request_type=webhook.ListWebhooksRequest): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhooks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_webhooks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWebhooksAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_webhooks_async_from_dict(): - await test_list_webhooks_async(request_type=dict) - - -def test_list_webhooks_field_headers(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.ListWebhooksRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - call.return_value = webhook.ListWebhooksResponse() - client.list_webhooks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_webhooks_field_headers_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.ListWebhooksRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse()) - await client.list_webhooks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_webhooks_flattened(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.ListWebhooksResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_webhooks( - parent='parent_value', - ) - - # Establish that the 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_webhooks_flattened_error(): - client = WebhooksClient( - credentials=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_webhooks( - webhook.ListWebhooksRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_webhooks_flattened_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.ListWebhooksResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_webhooks( - 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_webhooks_flattened_error_async(): - client = WebhooksAsyncClient( - credentials=ga_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_webhooks( - webhook.ListWebhooksRequest(), - parent='parent_value', - ) - - -def test_list_webhooks_pager(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - webhook.Webhook(), - ], - next_page_token='abc', - ), - webhook.ListWebhooksResponse( - webhooks=[], - next_page_token='def', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - ], - next_page_token='ghi', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_webhooks(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, webhook.Webhook) - for i in results) - -def test_list_webhooks_pages(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - webhook.Webhook(), - ], - next_page_token='abc', - ), - webhook.ListWebhooksResponse( - webhooks=[], - next_page_token='def', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - ], - next_page_token='ghi', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - ], - ), - RuntimeError, - ) - pages = list(client.list_webhooks(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_webhooks_async_pager(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - webhook.Webhook(), - ], - next_page_token='abc', - ), - webhook.ListWebhooksResponse( - webhooks=[], - next_page_token='def', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - ], - next_page_token='ghi', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_webhooks(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, webhook.Webhook) - for i in responses) - -@pytest.mark.asyncio -async def test_list_webhooks_async_pages(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - webhook.Webhook(), - ], - next_page_token='abc', - ), - webhook.ListWebhooksResponse( - webhooks=[], - next_page_token='def', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - ], - next_page_token='ghi', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_webhooks(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_webhook(transport: str = 'grpc', request_type=webhook.GetWebhookRequest): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - generic_web_service=webhook.Webhook.GenericWebService(uri='uri_value'), - ) - response = client.get_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -def test_get_webhook_from_dict(): - test_get_webhook(request_type=dict) - - -def test_get_webhook_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebhooksClient( - credentials=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_webhook), - '__call__') as call: - client.get_webhook() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() - - -@pytest.mark.asyncio -async def test_get_webhook_async(transport: str = 'grpc_asyncio', request_type=webhook.GetWebhookRequest): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - )) - response = await client.get_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -@pytest.mark.asyncio -async def test_get_webhook_async_from_dict(): - await test_get_webhook_async(request_type=dict) - - -def test_get_webhook_field_headers(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.GetWebhookRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_webhook), - '__call__') as call: - call.return_value = webhook.Webhook() - client.get_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_webhook_field_headers_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.GetWebhookRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_webhook), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook()) - await client.get_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_webhook_flattened(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.Webhook() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_webhook( - name='name_value', - ) - - # Establish that the 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_webhook_flattened_error(): - client = WebhooksClient( - credentials=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_webhook( - webhook.GetWebhookRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_webhook_flattened_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.Webhook() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_webhook( - 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_webhook_flattened_error_async(): - client = WebhooksAsyncClient( - credentials=ga_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_webhook( - webhook.GetWebhookRequest(), - name='name_value', - ) - - -def test_create_webhook(transport: str = 'grpc', request_type=gcdc_webhook.CreateWebhookRequest): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri='uri_value'), - ) - response = client.create_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -def test_create_webhook_from_dict(): - test_create_webhook(request_type=dict) - - -def test_create_webhook_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebhooksClient( - credentials=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_webhook), - '__call__') as call: - client.create_webhook() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() - - -@pytest.mark.asyncio -async def test_create_webhook_async(transport: str = 'grpc_asyncio', request_type=gcdc_webhook.CreateWebhookRequest): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - )) - response = await client.create_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -@pytest.mark.asyncio -async def test_create_webhook_async_from_dict(): - await test_create_webhook_async(request_type=dict) - - -def test_create_webhook_field_headers(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_webhook.CreateWebhookRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_webhook), - '__call__') as call: - call.return_value = gcdc_webhook.Webhook() - client.create_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_webhook_field_headers_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_webhook.CreateWebhookRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_webhook), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) - await client.create_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_webhook_flattened(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_webhook( - parent='parent_value', - webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') - - -def test_create_webhook_flattened_error(): - client = WebhooksClient( - credentials=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_webhook( - gcdc_webhook.CreateWebhookRequest(), - parent='parent_value', - webhook=gcdc_webhook.Webhook(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_webhook_flattened_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_webhook( - parent='parent_value', - webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') - - -@pytest.mark.asyncio -async def test_create_webhook_flattened_error_async(): - client = WebhooksAsyncClient( - credentials=ga_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_webhook( - gcdc_webhook.CreateWebhookRequest(), - parent='parent_value', - webhook=gcdc_webhook.Webhook(name='name_value'), - ) - - -def test_update_webhook(transport: str = 'grpc', request_type=gcdc_webhook.UpdateWebhookRequest): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri='uri_value'), - ) - response = client.update_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -def test_update_webhook_from_dict(): - test_update_webhook(request_type=dict) - - -def test_update_webhook_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebhooksClient( - credentials=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_webhook), - '__call__') as call: - client.update_webhook() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() - - -@pytest.mark.asyncio -async def test_update_webhook_async(transport: str = 'grpc_asyncio', request_type=gcdc_webhook.UpdateWebhookRequest): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - )) - response = await client.update_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -@pytest.mark.asyncio -async def test_update_webhook_async_from_dict(): - await test_update_webhook_async(request_type=dict) - - -def test_update_webhook_field_headers(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_webhook.UpdateWebhookRequest() - - request.webhook.name = 'webhook.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_webhook), - '__call__') as call: - call.return_value = gcdc_webhook.Webhook() - client.update_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'webhook.name=webhook.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_webhook_field_headers_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_webhook.UpdateWebhookRequest() - - request.webhook.name = 'webhook.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_webhook), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) - await client.update_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'webhook.name=webhook.name/value', - ) in kw['metadata'] - - -def test_update_webhook_flattened(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_webhook( - webhook=gcdc_webhook.Webhook(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].webhook == gcdc_webhook.Webhook(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_webhook_flattened_error(): - client = WebhooksClient( - credentials=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_webhook( - gcdc_webhook.UpdateWebhookRequest(), - webhook=gcdc_webhook.Webhook(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_webhook_flattened_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_webhook( - webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_webhook_flattened_error_async(): - client = WebhooksAsyncClient( - credentials=ga_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_webhook( - gcdc_webhook.UpdateWebhookRequest(), - webhook=gcdc_webhook.Webhook(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_webhook(transport: str = 'grpc', request_type=webhook.DeleteWebhookRequest): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_webhook_from_dict(): - test_delete_webhook(request_type=dict) - - -def test_delete_webhook_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebhooksClient( - credentials=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_webhook), - '__call__') as call: - client.delete_webhook() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() - - -@pytest.mark.asyncio -async def test_delete_webhook_async(transport: str = 'grpc_asyncio', request_type=webhook.DeleteWebhookRequest): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_webhook_async_from_dict(): - await test_delete_webhook_async(request_type=dict) - - -def test_delete_webhook_field_headers(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.DeleteWebhookRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_webhook), - '__call__') as call: - call.return_value = None - client.delete_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_webhook_field_headers_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.DeleteWebhookRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_webhook), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_webhook_flattened(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_webhook( - name='name_value', - ) - - # Establish that the 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_webhook_flattened_error(): - client = WebhooksClient( - credentials=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_webhook( - webhook.DeleteWebhookRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_webhook_flattened_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_webhook), - '__call__') as call: - # 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_webhook( - 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_webhook_flattened_error_async(): - client = WebhooksAsyncClient( - credentials=ga_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_webhook( - webhook.DeleteWebhookRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebhooksGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebhooksGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebhooksClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WebhooksGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebhooksClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebhooksGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WebhooksClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebhooksGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WebhooksGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WebhooksGrpcTransport, - transports.WebhooksGrpcAsyncIOTransport, -]) -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 = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WebhooksGrpcTransport, - ) - -def test_webhooks_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebhooksTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_webhooks_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WebhooksTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_webhooks', - 'get_webhook', - 'create_webhook', - 'update_webhook', - 'delete_webhook', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_webhooks_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebhooksTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_webhooks_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebhooksTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_webhooks_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebhooksTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_webhooks_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - WebhooksClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_webhooks_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - WebhooksClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebhooksGrpcTransport, - transports.WebhooksGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_webhooks_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebhooksGrpcTransport, - transports.WebhooksGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_webhooks_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.WebhooksGrpcTransport, grpc_helpers), - (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_webhooks_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.WebhooksGrpcTransport, grpc_helpers), - (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_webhooks_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.WebhooksGrpcTransport, grpc_helpers), - (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_webhooks_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) -def test_webhooks_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = 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_webhooks_host_no_port(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_webhooks_host_with_port(): - client = WebhooksClient( - 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_webhooks_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebhooksGrpcTransport( - 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_webhooks_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebhooksGrpcAsyncIOTransport( - 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.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) -def test_webhooks_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.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) -def test_webhooks_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_service_path(): - project = "squid" - location = "clam" - namespace = "whelk" - service = "octopus" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - actual = WebhooksClient.service_path(project, location, namespace, service) - assert expected == actual - - -def test_parse_service_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "namespace": "cuttlefish", - "service": "mussel", - } - path = WebhooksClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.parse_service_path(path) - assert expected == actual - -def test_webhook_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - webhook = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = WebhooksClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "webhook": "octopus", - } - path = WebhooksClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WebhooksClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = WebhooksClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = WebhooksClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = WebhooksClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WebhooksClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = WebhooksClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = WebhooksClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = WebhooksClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.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 = WebhooksClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = WebhooksClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.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.WebhooksTransport, '_prep_wrapped_messages') as prep: - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WebhooksTransport, '_prep_wrapped_messages') as prep: - transport_class = WebhooksClient.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/v3beta1/MANIFEST.in b/owl-bot-staging/v3beta1/MANIFEST.in deleted file mode 100644 index 8a0b3570..00000000 --- a/owl-bot-staging/v3beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/dialogflowcx *.py -recursive-include google/cloud/dialogflowcx_v3beta1 *.py diff --git a/owl-bot-staging/v3beta1/README.rst b/owl-bot-staging/v3beta1/README.rst deleted file mode 100644 index bfe57a44..00000000 --- a/owl-bot-staging/v3beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Dialogflowcx 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 Dialogflowcx 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/v3beta1/docs/conf.py b/owl-bot-staging/v3beta1/docs/conf.py deleted file mode 100644 index 814121cd..00000000 --- a/owl-bot-staging/v3beta1/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-dialogflowcx 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-dialogflowcx" -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-dialogflowcx-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-dialogflowcx.tex", - u"google-cloud-dialogflowcx 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-dialogflowcx", - u"Google Cloud Dialogflowcx 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-dialogflowcx", - u"google-cloud-dialogflowcx Documentation", - author, - "google-cloud-dialogflowcx", - "GAPIC library for Google Cloud Dialogflowcx 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/v3beta1/docs/dialogflowcx_v3beta1/agents.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/agents.rst deleted file mode 100644 index 511ac6f9..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/agents.rst +++ /dev/null @@ -1,10 +0,0 @@ -Agents ------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.agents - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.agents.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/entity_types.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/entity_types.rst deleted file mode 100644 index 3878a96e..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/entity_types.rst +++ /dev/null @@ -1,10 +0,0 @@ -EntityTypes ------------------------------ - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.entity_types - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.entity_types.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/environments.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/environments.rst deleted file mode 100644 index 0e31d34d..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/environments.rst +++ /dev/null @@ -1,10 +0,0 @@ -Environments ------------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.environments - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.environments.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/experiments.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/experiments.rst deleted file mode 100644 index 5c185e4f..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/experiments.rst +++ /dev/null @@ -1,10 +0,0 @@ -Experiments ------------------------------ - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.experiments - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.experiments.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/flows.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/flows.rst deleted file mode 100644 index 0183ff3b..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/flows.rst +++ /dev/null @@ -1,10 +0,0 @@ -Flows ------------------------ - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.flows - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.flows.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/intents.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/intents.rst deleted file mode 100644 index 3bf9d37c..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/intents.rst +++ /dev/null @@ -1,10 +0,0 @@ -Intents -------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.intents - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.intents.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/pages.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/pages.rst deleted file mode 100644 index be3f1b16..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/pages.rst +++ /dev/null @@ -1,10 +0,0 @@ -Pages ------------------------ - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.pages - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.pages.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/security_settings_service.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/security_settings_service.rst deleted file mode 100644 index 0489568a..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/security_settings_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecuritySettingsService ------------------------------------------ - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.security_settings_service - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.security_settings_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/services.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/services.rst deleted file mode 100644 index 03f147db..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/services.rst +++ /dev/null @@ -1,19 +0,0 @@ -Services for Google Cloud Dialogflowcx v3beta1 API -================================================== -.. toctree:: - :maxdepth: 2 - - agents - entity_types - environments - experiments - flows - intents - pages - security_settings_service - session_entity_types - sessions - test_cases - transition_route_groups - versions - webhooks diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/session_entity_types.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/session_entity_types.rst deleted file mode 100644 index a6248835..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/session_entity_types.rst +++ /dev/null @@ -1,10 +0,0 @@ -SessionEntityTypes ------------------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.session_entity_types - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.session_entity_types.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/sessions.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/sessions.rst deleted file mode 100644 index 3f792bf8..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/sessions.rst +++ /dev/null @@ -1,6 +0,0 @@ -Sessions --------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.sessions - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/test_cases.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/test_cases.rst deleted file mode 100644 index a212f0b4..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/test_cases.rst +++ /dev/null @@ -1,10 +0,0 @@ -TestCases ---------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.test_cases - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/transition_route_groups.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/transition_route_groups.rst deleted file mode 100644 index 9b29ddf9..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/transition_route_groups.rst +++ /dev/null @@ -1,10 +0,0 @@ -TransitionRouteGroups ---------------------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.transition_route_groups - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/types.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/types.rst deleted file mode 100644 index a7388b27..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Dialogflowcx v3beta1 API -=============================================== - -.. automodule:: google.cloud.dialogflowcx_v3beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/versions.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/versions.rst deleted file mode 100644 index 6617fb66..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/versions.rst +++ /dev/null @@ -1,10 +0,0 @@ -Versions --------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.versions - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.versions.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/webhooks.rst b/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/webhooks.rst deleted file mode 100644 index 4fa96e0f..00000000 --- a/owl-bot-staging/v3beta1/docs/dialogflowcx_v3beta1/webhooks.rst +++ /dev/null @@ -1,10 +0,0 @@ -Webhooks --------------------------- - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.webhooks - :members: - :inherited-members: - -.. automodule:: google.cloud.dialogflowcx_v3beta1.services.webhooks.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v3beta1/docs/index.rst b/owl-bot-staging/v3beta1/docs/index.rst deleted file mode 100644 index 7944398b..00000000 --- a/owl-bot-staging/v3beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - dialogflowcx_v3beta1/services - dialogflowcx_v3beta1/types diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/__init__.py deleted file mode 100644 index 8e0cebda..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/__init__.py +++ /dev/null @@ -1,451 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.agents.client import AgentsClient -from google.cloud.dialogflowcx_v3beta1.services.agents.async_client import AgentsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.entity_types.client import EntityTypesClient -from google.cloud.dialogflowcx_v3beta1.services.entity_types.async_client import EntityTypesAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.environments.client import EnvironmentsClient -from google.cloud.dialogflowcx_v3beta1.services.environments.async_client import EnvironmentsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.experiments.client import ExperimentsClient -from google.cloud.dialogflowcx_v3beta1.services.experiments.async_client import ExperimentsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.flows.client import FlowsClient -from google.cloud.dialogflowcx_v3beta1.services.flows.async_client import FlowsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.intents.client import IntentsClient -from google.cloud.dialogflowcx_v3beta1.services.intents.async_client import IntentsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.pages.client import PagesClient -from google.cloud.dialogflowcx_v3beta1.services.pages.async_client import PagesAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.security_settings_service.client import SecuritySettingsServiceClient -from google.cloud.dialogflowcx_v3beta1.services.security_settings_service.async_client import SecuritySettingsServiceAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.session_entity_types.client import SessionEntityTypesClient -from google.cloud.dialogflowcx_v3beta1.services.session_entity_types.async_client import SessionEntityTypesAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.sessions.client import SessionsClient -from google.cloud.dialogflowcx_v3beta1.services.sessions.async_client import SessionsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.test_cases.client import TestCasesClient -from google.cloud.dialogflowcx_v3beta1.services.test_cases.async_client import TestCasesAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.client import TransitionRouteGroupsClient -from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.async_client import TransitionRouteGroupsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.versions.client import VersionsClient -from google.cloud.dialogflowcx_v3beta1.services.versions.async_client import VersionsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.webhooks.client import WebhooksClient -from google.cloud.dialogflowcx_v3beta1.services.webhooks.async_client import WebhooksAsyncClient - -from google.cloud.dialogflowcx_v3beta1.types.agent import Agent -from google.cloud.dialogflowcx_v3beta1.types.agent import AgentValidationResult -from google.cloud.dialogflowcx_v3beta1.types.agent import CreateAgentRequest -from google.cloud.dialogflowcx_v3beta1.types.agent import DeleteAgentRequest -from google.cloud.dialogflowcx_v3beta1.types.agent import ExportAgentRequest -from google.cloud.dialogflowcx_v3beta1.types.agent import ExportAgentResponse -from google.cloud.dialogflowcx_v3beta1.types.agent import GetAgentRequest -from google.cloud.dialogflowcx_v3beta1.types.agent import GetAgentValidationResultRequest -from google.cloud.dialogflowcx_v3beta1.types.agent import ListAgentsRequest -from google.cloud.dialogflowcx_v3beta1.types.agent import ListAgentsResponse -from google.cloud.dialogflowcx_v3beta1.types.agent import RestoreAgentRequest -from google.cloud.dialogflowcx_v3beta1.types.agent import SpeechToTextSettings -from google.cloud.dialogflowcx_v3beta1.types.agent import UpdateAgentRequest -from google.cloud.dialogflowcx_v3beta1.types.agent import ValidateAgentRequest -from google.cloud.dialogflowcx_v3beta1.types.audio_config import InputAudioConfig -from google.cloud.dialogflowcx_v3beta1.types.audio_config import OutputAudioConfig -from google.cloud.dialogflowcx_v3beta1.types.audio_config import SpeechWordInfo -from google.cloud.dialogflowcx_v3beta1.types.audio_config import SynthesizeSpeechConfig -from google.cloud.dialogflowcx_v3beta1.types.audio_config import VoiceSelectionParams -from google.cloud.dialogflowcx_v3beta1.types.audio_config import AudioEncoding -from google.cloud.dialogflowcx_v3beta1.types.audio_config import OutputAudioEncoding -from google.cloud.dialogflowcx_v3beta1.types.audio_config import SpeechModelVariant -from google.cloud.dialogflowcx_v3beta1.types.audio_config import SsmlVoiceGender -from google.cloud.dialogflowcx_v3beta1.types.entity_type import CreateEntityTypeRequest -from google.cloud.dialogflowcx_v3beta1.types.entity_type import DeleteEntityTypeRequest -from google.cloud.dialogflowcx_v3beta1.types.entity_type import EntityType -from google.cloud.dialogflowcx_v3beta1.types.entity_type import GetEntityTypeRequest -from google.cloud.dialogflowcx_v3beta1.types.entity_type import ListEntityTypesRequest -from google.cloud.dialogflowcx_v3beta1.types.entity_type import ListEntityTypesResponse -from google.cloud.dialogflowcx_v3beta1.types.entity_type import UpdateEntityTypeRequest -from google.cloud.dialogflowcx_v3beta1.types.environment import ContinuousTestResult -from google.cloud.dialogflowcx_v3beta1.types.environment import CreateEnvironmentRequest -from google.cloud.dialogflowcx_v3beta1.types.environment import DeleteEnvironmentRequest -from google.cloud.dialogflowcx_v3beta1.types.environment import Environment -from google.cloud.dialogflowcx_v3beta1.types.environment import GetEnvironmentRequest -from google.cloud.dialogflowcx_v3beta1.types.environment import ListContinuousTestResultsRequest -from google.cloud.dialogflowcx_v3beta1.types.environment import ListContinuousTestResultsResponse -from google.cloud.dialogflowcx_v3beta1.types.environment import ListEnvironmentsRequest -from google.cloud.dialogflowcx_v3beta1.types.environment import ListEnvironmentsResponse -from google.cloud.dialogflowcx_v3beta1.types.environment import LookupEnvironmentHistoryRequest -from google.cloud.dialogflowcx_v3beta1.types.environment import LookupEnvironmentHistoryResponse -from google.cloud.dialogflowcx_v3beta1.types.environment import RunContinuousTestMetadata -from google.cloud.dialogflowcx_v3beta1.types.environment import RunContinuousTestRequest -from google.cloud.dialogflowcx_v3beta1.types.environment import RunContinuousTestResponse -from google.cloud.dialogflowcx_v3beta1.types.environment import UpdateEnvironmentRequest -from google.cloud.dialogflowcx_v3beta1.types.experiment import CreateExperimentRequest -from google.cloud.dialogflowcx_v3beta1.types.experiment import DeleteExperimentRequest -from google.cloud.dialogflowcx_v3beta1.types.experiment import Experiment -from google.cloud.dialogflowcx_v3beta1.types.experiment import GetExperimentRequest -from google.cloud.dialogflowcx_v3beta1.types.experiment import ListExperimentsRequest -from google.cloud.dialogflowcx_v3beta1.types.experiment import ListExperimentsResponse -from google.cloud.dialogflowcx_v3beta1.types.experiment import StartExperimentRequest -from google.cloud.dialogflowcx_v3beta1.types.experiment import StopExperimentRequest -from google.cloud.dialogflowcx_v3beta1.types.experiment import UpdateExperimentRequest -from google.cloud.dialogflowcx_v3beta1.types.experiment import VariantsHistory -from google.cloud.dialogflowcx_v3beta1.types.experiment import VersionVariants -from google.cloud.dialogflowcx_v3beta1.types.flow import CreateFlowRequest -from google.cloud.dialogflowcx_v3beta1.types.flow import DeleteFlowRequest -from google.cloud.dialogflowcx_v3beta1.types.flow import ExportFlowRequest -from google.cloud.dialogflowcx_v3beta1.types.flow import ExportFlowResponse -from google.cloud.dialogflowcx_v3beta1.types.flow import Flow -from google.cloud.dialogflowcx_v3beta1.types.flow import FlowValidationResult -from google.cloud.dialogflowcx_v3beta1.types.flow import GetFlowRequest -from google.cloud.dialogflowcx_v3beta1.types.flow import GetFlowValidationResultRequest -from google.cloud.dialogflowcx_v3beta1.types.flow import ImportFlowRequest -from google.cloud.dialogflowcx_v3beta1.types.flow import ImportFlowResponse -from google.cloud.dialogflowcx_v3beta1.types.flow import ListFlowsRequest -from google.cloud.dialogflowcx_v3beta1.types.flow import ListFlowsResponse -from google.cloud.dialogflowcx_v3beta1.types.flow import NluSettings -from google.cloud.dialogflowcx_v3beta1.types.flow import TrainFlowRequest -from google.cloud.dialogflowcx_v3beta1.types.flow import UpdateFlowRequest -from google.cloud.dialogflowcx_v3beta1.types.flow import ValidateFlowRequest -from google.cloud.dialogflowcx_v3beta1.types.fulfillment import Fulfillment -from google.cloud.dialogflowcx_v3beta1.types.intent import CreateIntentRequest -from google.cloud.dialogflowcx_v3beta1.types.intent import DeleteIntentRequest -from google.cloud.dialogflowcx_v3beta1.types.intent import GetIntentRequest -from google.cloud.dialogflowcx_v3beta1.types.intent import Intent -from google.cloud.dialogflowcx_v3beta1.types.intent import ListIntentsRequest -from google.cloud.dialogflowcx_v3beta1.types.intent import ListIntentsResponse -from google.cloud.dialogflowcx_v3beta1.types.intent import UpdateIntentRequest -from google.cloud.dialogflowcx_v3beta1.types.intent import IntentView -from google.cloud.dialogflowcx_v3beta1.types.page import CreatePageRequest -from google.cloud.dialogflowcx_v3beta1.types.page import DeletePageRequest -from google.cloud.dialogflowcx_v3beta1.types.page import EventHandler -from google.cloud.dialogflowcx_v3beta1.types.page import Form -from google.cloud.dialogflowcx_v3beta1.types.page import GetPageRequest -from google.cloud.dialogflowcx_v3beta1.types.page import ListPagesRequest -from google.cloud.dialogflowcx_v3beta1.types.page import ListPagesResponse -from google.cloud.dialogflowcx_v3beta1.types.page import Page -from google.cloud.dialogflowcx_v3beta1.types.page import TransitionRoute -from google.cloud.dialogflowcx_v3beta1.types.page import UpdatePageRequest -from google.cloud.dialogflowcx_v3beta1.types.response_message import ResponseMessage -from google.cloud.dialogflowcx_v3beta1.types.security_settings import CreateSecuritySettingsRequest -from google.cloud.dialogflowcx_v3beta1.types.security_settings import DeleteSecuritySettingsRequest -from google.cloud.dialogflowcx_v3beta1.types.security_settings import GetSecuritySettingsRequest -from google.cloud.dialogflowcx_v3beta1.types.security_settings import ListSecuritySettingsRequest -from google.cloud.dialogflowcx_v3beta1.types.security_settings import ListSecuritySettingsResponse -from google.cloud.dialogflowcx_v3beta1.types.security_settings import SecuritySettings -from google.cloud.dialogflowcx_v3beta1.types.security_settings import UpdateSecuritySettingsRequest -from google.cloud.dialogflowcx_v3beta1.types.session import AudioInput -from google.cloud.dialogflowcx_v3beta1.types.session import DetectIntentRequest -from google.cloud.dialogflowcx_v3beta1.types.session import DetectIntentResponse -from google.cloud.dialogflowcx_v3beta1.types.session import DtmfInput -from google.cloud.dialogflowcx_v3beta1.types.session import EventInput -from google.cloud.dialogflowcx_v3beta1.types.session import FulfillIntentRequest -from google.cloud.dialogflowcx_v3beta1.types.session import FulfillIntentResponse -from google.cloud.dialogflowcx_v3beta1.types.session import IntentInput -from google.cloud.dialogflowcx_v3beta1.types.session import Match -from google.cloud.dialogflowcx_v3beta1.types.session import MatchIntentRequest -from google.cloud.dialogflowcx_v3beta1.types.session import MatchIntentResponse -from google.cloud.dialogflowcx_v3beta1.types.session import QueryInput -from google.cloud.dialogflowcx_v3beta1.types.session import QueryParameters -from google.cloud.dialogflowcx_v3beta1.types.session import QueryResult -from google.cloud.dialogflowcx_v3beta1.types.session import SentimentAnalysisResult -from google.cloud.dialogflowcx_v3beta1.types.session import StreamingDetectIntentRequest -from google.cloud.dialogflowcx_v3beta1.types.session import StreamingDetectIntentResponse -from google.cloud.dialogflowcx_v3beta1.types.session import StreamingRecognitionResult -from google.cloud.dialogflowcx_v3beta1.types.session import TextInput -from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import CreateSessionEntityTypeRequest -from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import DeleteSessionEntityTypeRequest -from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import GetSessionEntityTypeRequest -from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import ListSessionEntityTypesRequest -from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import ListSessionEntityTypesResponse -from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import SessionEntityType -from google.cloud.dialogflowcx_v3beta1.types.session_entity_type import UpdateSessionEntityTypeRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import BatchDeleteTestCasesRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import BatchRunTestCasesMetadata -from google.cloud.dialogflowcx_v3beta1.types.test_case import BatchRunTestCasesRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import BatchRunTestCasesResponse -from google.cloud.dialogflowcx_v3beta1.types.test_case import CalculateCoverageRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import CalculateCoverageResponse -from google.cloud.dialogflowcx_v3beta1.types.test_case import ConversationTurn -from google.cloud.dialogflowcx_v3beta1.types.test_case import CreateTestCaseRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import ExportTestCasesMetadata -from google.cloud.dialogflowcx_v3beta1.types.test_case import ExportTestCasesRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import ExportTestCasesResponse -from google.cloud.dialogflowcx_v3beta1.types.test_case import GetTestCaseRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import GetTestCaseResultRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import ImportTestCasesMetadata -from google.cloud.dialogflowcx_v3beta1.types.test_case import ImportTestCasesRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import ImportTestCasesResponse -from google.cloud.dialogflowcx_v3beta1.types.test_case import IntentCoverage -from google.cloud.dialogflowcx_v3beta1.types.test_case import ListTestCaseResultsRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import ListTestCaseResultsResponse -from google.cloud.dialogflowcx_v3beta1.types.test_case import ListTestCasesRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import ListTestCasesResponse -from google.cloud.dialogflowcx_v3beta1.types.test_case import RunTestCaseMetadata -from google.cloud.dialogflowcx_v3beta1.types.test_case import RunTestCaseRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import RunTestCaseResponse -from google.cloud.dialogflowcx_v3beta1.types.test_case import TestCase -from google.cloud.dialogflowcx_v3beta1.types.test_case import TestCaseError -from google.cloud.dialogflowcx_v3beta1.types.test_case import TestCaseResult -from google.cloud.dialogflowcx_v3beta1.types.test_case import TestConfig -from google.cloud.dialogflowcx_v3beta1.types.test_case import TestError -from google.cloud.dialogflowcx_v3beta1.types.test_case import TestRunDifference -from google.cloud.dialogflowcx_v3beta1.types.test_case import TransitionCoverage -from google.cloud.dialogflowcx_v3beta1.types.test_case import TransitionRouteGroupCoverage -from google.cloud.dialogflowcx_v3beta1.types.test_case import UpdateTestCaseRequest -from google.cloud.dialogflowcx_v3beta1.types.test_case import TestResult -from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import CreateTransitionRouteGroupRequest -from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import DeleteTransitionRouteGroupRequest -from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import GetTransitionRouteGroupRequest -from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import ListTransitionRouteGroupsRequest -from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import ListTransitionRouteGroupsResponse -from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import TransitionRouteGroup -from google.cloud.dialogflowcx_v3beta1.types.transition_route_group import UpdateTransitionRouteGroupRequest -from google.cloud.dialogflowcx_v3beta1.types.validation_message import ResourceName -from google.cloud.dialogflowcx_v3beta1.types.validation_message import ValidationMessage -from google.cloud.dialogflowcx_v3beta1.types.version import CreateVersionOperationMetadata -from google.cloud.dialogflowcx_v3beta1.types.version import CreateVersionRequest -from google.cloud.dialogflowcx_v3beta1.types.version import DeleteVersionRequest -from google.cloud.dialogflowcx_v3beta1.types.version import GetVersionRequest -from google.cloud.dialogflowcx_v3beta1.types.version import ListVersionsRequest -from google.cloud.dialogflowcx_v3beta1.types.version import ListVersionsResponse -from google.cloud.dialogflowcx_v3beta1.types.version import LoadVersionRequest -from google.cloud.dialogflowcx_v3beta1.types.version import UpdateVersionRequest -from google.cloud.dialogflowcx_v3beta1.types.version import Version -from google.cloud.dialogflowcx_v3beta1.types.webhook import CreateWebhookRequest -from google.cloud.dialogflowcx_v3beta1.types.webhook import DeleteWebhookRequest -from google.cloud.dialogflowcx_v3beta1.types.webhook import GetWebhookRequest -from google.cloud.dialogflowcx_v3beta1.types.webhook import ListWebhooksRequest -from google.cloud.dialogflowcx_v3beta1.types.webhook import ListWebhooksResponse -from google.cloud.dialogflowcx_v3beta1.types.webhook import PageInfo -from google.cloud.dialogflowcx_v3beta1.types.webhook import SessionInfo -from google.cloud.dialogflowcx_v3beta1.types.webhook import UpdateWebhookRequest -from google.cloud.dialogflowcx_v3beta1.types.webhook import Webhook -from google.cloud.dialogflowcx_v3beta1.types.webhook import WebhookRequest -from google.cloud.dialogflowcx_v3beta1.types.webhook import WebhookResponse - -__all__ = ('AgentsClient', - 'AgentsAsyncClient', - 'EntityTypesClient', - 'EntityTypesAsyncClient', - 'EnvironmentsClient', - 'EnvironmentsAsyncClient', - 'ExperimentsClient', - 'ExperimentsAsyncClient', - 'FlowsClient', - 'FlowsAsyncClient', - 'IntentsClient', - 'IntentsAsyncClient', - 'PagesClient', - 'PagesAsyncClient', - 'SecuritySettingsServiceClient', - 'SecuritySettingsServiceAsyncClient', - 'SessionEntityTypesClient', - 'SessionEntityTypesAsyncClient', - 'SessionsClient', - 'SessionsAsyncClient', - 'TestCasesClient', - 'TestCasesAsyncClient', - 'TransitionRouteGroupsClient', - 'TransitionRouteGroupsAsyncClient', - 'VersionsClient', - 'VersionsAsyncClient', - 'WebhooksClient', - 'WebhooksAsyncClient', - 'Agent', - 'AgentValidationResult', - 'CreateAgentRequest', - 'DeleteAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'GetAgentRequest', - 'GetAgentValidationResultRequest', - 'ListAgentsRequest', - 'ListAgentsResponse', - 'RestoreAgentRequest', - 'SpeechToTextSettings', - 'UpdateAgentRequest', - 'ValidateAgentRequest', - 'InputAudioConfig', - 'OutputAudioConfig', - 'SpeechWordInfo', - 'SynthesizeSpeechConfig', - 'VoiceSelectionParams', - 'AudioEncoding', - 'OutputAudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'CreateEntityTypeRequest', - 'DeleteEntityTypeRequest', - 'EntityType', - 'GetEntityTypeRequest', - 'ListEntityTypesRequest', - 'ListEntityTypesResponse', - 'UpdateEntityTypeRequest', - 'ContinuousTestResult', - 'CreateEnvironmentRequest', - 'DeleteEnvironmentRequest', - 'Environment', - 'GetEnvironmentRequest', - 'ListContinuousTestResultsRequest', - 'ListContinuousTestResultsResponse', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LookupEnvironmentHistoryRequest', - 'LookupEnvironmentHistoryResponse', - 'RunContinuousTestMetadata', - 'RunContinuousTestRequest', - 'RunContinuousTestResponse', - 'UpdateEnvironmentRequest', - 'CreateExperimentRequest', - 'DeleteExperimentRequest', - 'Experiment', - 'GetExperimentRequest', - 'ListExperimentsRequest', - 'ListExperimentsResponse', - 'StartExperimentRequest', - 'StopExperimentRequest', - 'UpdateExperimentRequest', - 'VariantsHistory', - 'VersionVariants', - 'CreateFlowRequest', - 'DeleteFlowRequest', - 'ExportFlowRequest', - 'ExportFlowResponse', - 'Flow', - 'FlowValidationResult', - 'GetFlowRequest', - 'GetFlowValidationResultRequest', - 'ImportFlowRequest', - 'ImportFlowResponse', - 'ListFlowsRequest', - 'ListFlowsResponse', - 'NluSettings', - 'TrainFlowRequest', - 'UpdateFlowRequest', - 'ValidateFlowRequest', - 'Fulfillment', - 'CreateIntentRequest', - 'DeleteIntentRequest', - 'GetIntentRequest', - 'Intent', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'UpdateIntentRequest', - 'IntentView', - 'CreatePageRequest', - 'DeletePageRequest', - 'EventHandler', - 'Form', - 'GetPageRequest', - 'ListPagesRequest', - 'ListPagesResponse', - 'Page', - 'TransitionRoute', - 'UpdatePageRequest', - 'ResponseMessage', - 'CreateSecuritySettingsRequest', - 'DeleteSecuritySettingsRequest', - 'GetSecuritySettingsRequest', - 'ListSecuritySettingsRequest', - 'ListSecuritySettingsResponse', - 'SecuritySettings', - 'UpdateSecuritySettingsRequest', - 'AudioInput', - 'DetectIntentRequest', - 'DetectIntentResponse', - 'DtmfInput', - 'EventInput', - 'FulfillIntentRequest', - 'FulfillIntentResponse', - 'IntentInput', - 'Match', - 'MatchIntentRequest', - 'MatchIntentResponse', - 'QueryInput', - 'QueryParameters', - 'QueryResult', - 'SentimentAnalysisResult', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'TextInput', - 'CreateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - 'GetSessionEntityTypeRequest', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'SessionEntityType', - 'UpdateSessionEntityTypeRequest', - 'BatchDeleteTestCasesRequest', - 'BatchRunTestCasesMetadata', - 'BatchRunTestCasesRequest', - 'BatchRunTestCasesResponse', - 'CalculateCoverageRequest', - 'CalculateCoverageResponse', - 'ConversationTurn', - 'CreateTestCaseRequest', - 'ExportTestCasesMetadata', - 'ExportTestCasesRequest', - 'ExportTestCasesResponse', - 'GetTestCaseRequest', - 'GetTestCaseResultRequest', - 'ImportTestCasesMetadata', - 'ImportTestCasesRequest', - 'ImportTestCasesResponse', - 'IntentCoverage', - 'ListTestCaseResultsRequest', - 'ListTestCaseResultsResponse', - 'ListTestCasesRequest', - 'ListTestCasesResponse', - 'RunTestCaseMetadata', - 'RunTestCaseRequest', - 'RunTestCaseResponse', - 'TestCase', - 'TestCaseError', - 'TestCaseResult', - 'TestConfig', - 'TestError', - 'TestRunDifference', - 'TransitionCoverage', - 'TransitionRouteGroupCoverage', - 'UpdateTestCaseRequest', - 'TestResult', - 'CreateTransitionRouteGroupRequest', - 'DeleteTransitionRouteGroupRequest', - 'GetTransitionRouteGroupRequest', - 'ListTransitionRouteGroupsRequest', - 'ListTransitionRouteGroupsResponse', - 'TransitionRouteGroup', - 'UpdateTransitionRouteGroupRequest', - 'ResourceName', - 'ValidationMessage', - 'CreateVersionOperationMetadata', - 'CreateVersionRequest', - 'DeleteVersionRequest', - 'GetVersionRequest', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'LoadVersionRequest', - 'UpdateVersionRequest', - 'Version', - 'CreateWebhookRequest', - 'DeleteWebhookRequest', - 'GetWebhookRequest', - 'ListWebhooksRequest', - 'ListWebhooksResponse', - 'PageInfo', - 'SessionInfo', - 'UpdateWebhookRequest', - 'Webhook', - 'WebhookRequest', - 'WebhookResponse', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/py.typed b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/py.typed deleted file mode 100644 index 60fdca49..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-dialogflowcx package uses inline types. diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/__init__.py deleted file mode 100644 index 71e275f7..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/__init__.py +++ /dev/null @@ -1,452 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.entity_types import EntityTypesClient -from .services.entity_types import EntityTypesAsyncClient -from .services.environments import EnvironmentsClient -from .services.environments import EnvironmentsAsyncClient -from .services.experiments import ExperimentsClient -from .services.experiments import ExperimentsAsyncClient -from .services.flows import FlowsClient -from .services.flows import FlowsAsyncClient -from .services.intents import IntentsClient -from .services.intents import IntentsAsyncClient -from .services.pages import PagesClient -from .services.pages import PagesAsyncClient -from .services.security_settings_service import SecuritySettingsServiceClient -from .services.security_settings_service import SecuritySettingsServiceAsyncClient -from .services.session_entity_types import SessionEntityTypesClient -from .services.session_entity_types import SessionEntityTypesAsyncClient -from .services.sessions import SessionsClient -from .services.sessions import SessionsAsyncClient -from .services.test_cases import TestCasesClient -from .services.test_cases import TestCasesAsyncClient -from .services.transition_route_groups import TransitionRouteGroupsClient -from .services.transition_route_groups import TransitionRouteGroupsAsyncClient -from .services.versions import VersionsClient -from .services.versions import VersionsAsyncClient -from .services.webhooks import WebhooksClient -from .services.webhooks import WebhooksAsyncClient - -from .types.agent import Agent -from .types.agent import AgentValidationResult -from .types.agent import CreateAgentRequest -from .types.agent import DeleteAgentRequest -from .types.agent import ExportAgentRequest -from .types.agent import ExportAgentResponse -from .types.agent import GetAgentRequest -from .types.agent import GetAgentValidationResultRequest -from .types.agent import ListAgentsRequest -from .types.agent import ListAgentsResponse -from .types.agent import RestoreAgentRequest -from .types.agent import SpeechToTextSettings -from .types.agent import UpdateAgentRequest -from .types.agent import ValidateAgentRequest -from .types.audio_config import InputAudioConfig -from .types.audio_config import OutputAudioConfig -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.entity_type import CreateEntityTypeRequest -from .types.entity_type import DeleteEntityTypeRequest -from .types.entity_type import EntityType -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 ContinuousTestResult -from .types.environment import CreateEnvironmentRequest -from .types.environment import DeleteEnvironmentRequest -from .types.environment import Environment -from .types.environment import GetEnvironmentRequest -from .types.environment import ListContinuousTestResultsRequest -from .types.environment import ListContinuousTestResultsResponse -from .types.environment import ListEnvironmentsRequest -from .types.environment import ListEnvironmentsResponse -from .types.environment import LookupEnvironmentHistoryRequest -from .types.environment import LookupEnvironmentHistoryResponse -from .types.environment import RunContinuousTestMetadata -from .types.environment import RunContinuousTestRequest -from .types.environment import RunContinuousTestResponse -from .types.environment import UpdateEnvironmentRequest -from .types.experiment import CreateExperimentRequest -from .types.experiment import DeleteExperimentRequest -from .types.experiment import Experiment -from .types.experiment import GetExperimentRequest -from .types.experiment import ListExperimentsRequest -from .types.experiment import ListExperimentsResponse -from .types.experiment import StartExperimentRequest -from .types.experiment import StopExperimentRequest -from .types.experiment import UpdateExperimentRequest -from .types.experiment import VariantsHistory -from .types.experiment import VersionVariants -from .types.flow import CreateFlowRequest -from .types.flow import DeleteFlowRequest -from .types.flow import ExportFlowRequest -from .types.flow import ExportFlowResponse -from .types.flow import Flow -from .types.flow import FlowValidationResult -from .types.flow import GetFlowRequest -from .types.flow import GetFlowValidationResultRequest -from .types.flow import ImportFlowRequest -from .types.flow import ImportFlowResponse -from .types.flow import ListFlowsRequest -from .types.flow import ListFlowsResponse -from .types.flow import NluSettings -from .types.flow import TrainFlowRequest -from .types.flow import UpdateFlowRequest -from .types.flow import ValidateFlowRequest -from .types.fulfillment import Fulfillment -from .types.intent import CreateIntentRequest -from .types.intent import DeleteIntentRequest -from .types.intent import GetIntentRequest -from .types.intent import Intent -from .types.intent import ListIntentsRequest -from .types.intent import ListIntentsResponse -from .types.intent import UpdateIntentRequest -from .types.intent import IntentView -from .types.page import CreatePageRequest -from .types.page import DeletePageRequest -from .types.page import EventHandler -from .types.page import Form -from .types.page import GetPageRequest -from .types.page import ListPagesRequest -from .types.page import ListPagesResponse -from .types.page import Page -from .types.page import TransitionRoute -from .types.page import UpdatePageRequest -from .types.response_message import ResponseMessage -from .types.security_settings import CreateSecuritySettingsRequest -from .types.security_settings import DeleteSecuritySettingsRequest -from .types.security_settings import GetSecuritySettingsRequest -from .types.security_settings import ListSecuritySettingsRequest -from .types.security_settings import ListSecuritySettingsResponse -from .types.security_settings import SecuritySettings -from .types.security_settings import UpdateSecuritySettingsRequest -from .types.session import AudioInput -from .types.session import DetectIntentRequest -from .types.session import DetectIntentResponse -from .types.session import DtmfInput -from .types.session import EventInput -from .types.session import FulfillIntentRequest -from .types.session import FulfillIntentResponse -from .types.session import IntentInput -from .types.session import Match -from .types.session import MatchIntentRequest -from .types.session import MatchIntentResponse -from .types.session import QueryInput -from .types.session import QueryParameters -from .types.session import QueryResult -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.test_case import BatchDeleteTestCasesRequest -from .types.test_case import BatchRunTestCasesMetadata -from .types.test_case import BatchRunTestCasesRequest -from .types.test_case import BatchRunTestCasesResponse -from .types.test_case import CalculateCoverageRequest -from .types.test_case import CalculateCoverageResponse -from .types.test_case import ConversationTurn -from .types.test_case import CreateTestCaseRequest -from .types.test_case import ExportTestCasesMetadata -from .types.test_case import ExportTestCasesRequest -from .types.test_case import ExportTestCasesResponse -from .types.test_case import GetTestCaseRequest -from .types.test_case import GetTestCaseResultRequest -from .types.test_case import ImportTestCasesMetadata -from .types.test_case import ImportTestCasesRequest -from .types.test_case import ImportTestCasesResponse -from .types.test_case import IntentCoverage -from .types.test_case import ListTestCaseResultsRequest -from .types.test_case import ListTestCaseResultsResponse -from .types.test_case import ListTestCasesRequest -from .types.test_case import ListTestCasesResponse -from .types.test_case import RunTestCaseMetadata -from .types.test_case import RunTestCaseRequest -from .types.test_case import RunTestCaseResponse -from .types.test_case import TestCase -from .types.test_case import TestCaseError -from .types.test_case import TestCaseResult -from .types.test_case import TestConfig -from .types.test_case import TestError -from .types.test_case import TestRunDifference -from .types.test_case import TransitionCoverage -from .types.test_case import TransitionRouteGroupCoverage -from .types.test_case import UpdateTestCaseRequest -from .types.test_case import TestResult -from .types.transition_route_group import CreateTransitionRouteGroupRequest -from .types.transition_route_group import DeleteTransitionRouteGroupRequest -from .types.transition_route_group import GetTransitionRouteGroupRequest -from .types.transition_route_group import ListTransitionRouteGroupsRequest -from .types.transition_route_group import ListTransitionRouteGroupsResponse -from .types.transition_route_group import TransitionRouteGroup -from .types.transition_route_group import UpdateTransitionRouteGroupRequest -from .types.validation_message import ResourceName -from .types.validation_message import ValidationMessage -from .types.version import CreateVersionOperationMetadata -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 LoadVersionRequest -from .types.version import UpdateVersionRequest -from .types.version import Version -from .types.webhook import CreateWebhookRequest -from .types.webhook import DeleteWebhookRequest -from .types.webhook import GetWebhookRequest -from .types.webhook import ListWebhooksRequest -from .types.webhook import ListWebhooksResponse -from .types.webhook import PageInfo -from .types.webhook import SessionInfo -from .types.webhook import UpdateWebhookRequest -from .types.webhook import Webhook -from .types.webhook import WebhookRequest -from .types.webhook import WebhookResponse - -__all__ = ( - 'AgentsAsyncClient', - 'EntityTypesAsyncClient', - 'EnvironmentsAsyncClient', - 'ExperimentsAsyncClient', - 'FlowsAsyncClient', - 'IntentsAsyncClient', - 'PagesAsyncClient', - 'SecuritySettingsServiceAsyncClient', - 'SessionEntityTypesAsyncClient', - 'SessionsAsyncClient', - 'TestCasesAsyncClient', - 'TransitionRouteGroupsAsyncClient', - 'VersionsAsyncClient', - 'WebhooksAsyncClient', -'Agent', -'AgentValidationResult', -'AgentsClient', -'AudioEncoding', -'AudioInput', -'BatchDeleteTestCasesRequest', -'BatchRunTestCasesMetadata', -'BatchRunTestCasesRequest', -'BatchRunTestCasesResponse', -'CalculateCoverageRequest', -'CalculateCoverageResponse', -'ContinuousTestResult', -'ConversationTurn', -'CreateAgentRequest', -'CreateEntityTypeRequest', -'CreateEnvironmentRequest', -'CreateExperimentRequest', -'CreateFlowRequest', -'CreateIntentRequest', -'CreatePageRequest', -'CreateSecuritySettingsRequest', -'CreateSessionEntityTypeRequest', -'CreateTestCaseRequest', -'CreateTransitionRouteGroupRequest', -'CreateVersionOperationMetadata', -'CreateVersionRequest', -'CreateWebhookRequest', -'DeleteAgentRequest', -'DeleteEntityTypeRequest', -'DeleteEnvironmentRequest', -'DeleteExperimentRequest', -'DeleteFlowRequest', -'DeleteIntentRequest', -'DeletePageRequest', -'DeleteSecuritySettingsRequest', -'DeleteSessionEntityTypeRequest', -'DeleteTransitionRouteGroupRequest', -'DeleteVersionRequest', -'DeleteWebhookRequest', -'DetectIntentRequest', -'DetectIntentResponse', -'DtmfInput', -'EntityType', -'EntityTypesClient', -'Environment', -'EnvironmentsClient', -'EventHandler', -'EventInput', -'Experiment', -'ExperimentsClient', -'ExportAgentRequest', -'ExportAgentResponse', -'ExportFlowRequest', -'ExportFlowResponse', -'ExportTestCasesMetadata', -'ExportTestCasesRequest', -'ExportTestCasesResponse', -'Flow', -'FlowValidationResult', -'FlowsClient', -'Form', -'FulfillIntentRequest', -'FulfillIntentResponse', -'Fulfillment', -'GetAgentRequest', -'GetAgentValidationResultRequest', -'GetEntityTypeRequest', -'GetEnvironmentRequest', -'GetExperimentRequest', -'GetFlowRequest', -'GetFlowValidationResultRequest', -'GetIntentRequest', -'GetPageRequest', -'GetSecuritySettingsRequest', -'GetSessionEntityTypeRequest', -'GetTestCaseRequest', -'GetTestCaseResultRequest', -'GetTransitionRouteGroupRequest', -'GetVersionRequest', -'GetWebhookRequest', -'ImportFlowRequest', -'ImportFlowResponse', -'ImportTestCasesMetadata', -'ImportTestCasesRequest', -'ImportTestCasesResponse', -'InputAudioConfig', -'Intent', -'IntentCoverage', -'IntentInput', -'IntentView', -'IntentsClient', -'ListAgentsRequest', -'ListAgentsResponse', -'ListContinuousTestResultsRequest', -'ListContinuousTestResultsResponse', -'ListEntityTypesRequest', -'ListEntityTypesResponse', -'ListEnvironmentsRequest', -'ListEnvironmentsResponse', -'ListExperimentsRequest', -'ListExperimentsResponse', -'ListFlowsRequest', -'ListFlowsResponse', -'ListIntentsRequest', -'ListIntentsResponse', -'ListPagesRequest', -'ListPagesResponse', -'ListSecuritySettingsRequest', -'ListSecuritySettingsResponse', -'ListSessionEntityTypesRequest', -'ListSessionEntityTypesResponse', -'ListTestCaseResultsRequest', -'ListTestCaseResultsResponse', -'ListTestCasesRequest', -'ListTestCasesResponse', -'ListTransitionRouteGroupsRequest', -'ListTransitionRouteGroupsResponse', -'ListVersionsRequest', -'ListVersionsResponse', -'ListWebhooksRequest', -'ListWebhooksResponse', -'LoadVersionRequest', -'LookupEnvironmentHistoryRequest', -'LookupEnvironmentHistoryResponse', -'Match', -'MatchIntentRequest', -'MatchIntentResponse', -'NluSettings', -'OutputAudioConfig', -'OutputAudioEncoding', -'Page', -'PageInfo', -'PagesClient', -'QueryInput', -'QueryParameters', -'QueryResult', -'ResourceName', -'ResponseMessage', -'RestoreAgentRequest', -'RunContinuousTestMetadata', -'RunContinuousTestRequest', -'RunContinuousTestResponse', -'RunTestCaseMetadata', -'RunTestCaseRequest', -'RunTestCaseResponse', -'SecuritySettings', -'SecuritySettingsServiceClient', -'SentimentAnalysisResult', -'SessionEntityType', -'SessionEntityTypesClient', -'SessionInfo', -'SessionsClient', -'SpeechModelVariant', -'SpeechToTextSettings', -'SpeechWordInfo', -'SsmlVoiceGender', -'StartExperimentRequest', -'StopExperimentRequest', -'StreamingDetectIntentRequest', -'StreamingDetectIntentResponse', -'StreamingRecognitionResult', -'SynthesizeSpeechConfig', -'TestCase', -'TestCaseError', -'TestCaseResult', -'TestCasesClient', -'TestConfig', -'TestError', -'TestResult', -'TestRunDifference', -'TextInput', -'TrainFlowRequest', -'TransitionCoverage', -'TransitionRoute', -'TransitionRouteGroup', -'TransitionRouteGroupCoverage', -'TransitionRouteGroupsClient', -'UpdateAgentRequest', -'UpdateEntityTypeRequest', -'UpdateEnvironmentRequest', -'UpdateExperimentRequest', -'UpdateFlowRequest', -'UpdateIntentRequest', -'UpdatePageRequest', -'UpdateSecuritySettingsRequest', -'UpdateSessionEntityTypeRequest', -'UpdateTestCaseRequest', -'UpdateTransitionRouteGroupRequest', -'UpdateVersionRequest', -'UpdateWebhookRequest', -'ValidateAgentRequest', -'ValidateFlowRequest', -'ValidationMessage', -'VariantsHistory', -'Version', -'VersionVariants', -'VersionsClient', -'VoiceSelectionParams', -'Webhook', -'WebhookRequest', -'WebhookResponse', -'WebhooksClient', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json deleted file mode 100644 index 661610d7..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json +++ /dev/null @@ -1,1115 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.dialogflowcx_v3beta1", - "protoPackage": "google.cloud.dialogflow.cx.v3beta1", - "schema": "1.0", - "services": { - "Agents": { - "clients": { - "grpc": { - "libraryClient": "AgentsClient", - "rpcs": { - "CreateAgent": { - "methods": [ - "create_agent" - ] - }, - "DeleteAgent": { - "methods": [ - "delete_agent" - ] - }, - "ExportAgent": { - "methods": [ - "export_agent" - ] - }, - "GetAgent": { - "methods": [ - "get_agent" - ] - }, - "GetAgentValidationResult": { - "methods": [ - "get_agent_validation_result" - ] - }, - "ListAgents": { - "methods": [ - "list_agents" - ] - }, - "RestoreAgent": { - "methods": [ - "restore_agent" - ] - }, - "UpdateAgent": { - "methods": [ - "update_agent" - ] - }, - "ValidateAgent": { - "methods": [ - "validate_agent" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AgentsAsyncClient", - "rpcs": { - "CreateAgent": { - "methods": [ - "create_agent" - ] - }, - "DeleteAgent": { - "methods": [ - "delete_agent" - ] - }, - "ExportAgent": { - "methods": [ - "export_agent" - ] - }, - "GetAgent": { - "methods": [ - "get_agent" - ] - }, - "GetAgentValidationResult": { - "methods": [ - "get_agent_validation_result" - ] - }, - "ListAgents": { - "methods": [ - "list_agents" - ] - }, - "RestoreAgent": { - "methods": [ - "restore_agent" - ] - }, - "UpdateAgent": { - "methods": [ - "update_agent" - ] - }, - "ValidateAgent": { - "methods": [ - "validate_agent" - ] - } - } - } - } - }, - "EntityTypes": { - "clients": { - "grpc": { - "libraryClient": "EntityTypesClient", - "rpcs": { - "CreateEntityType": { - "methods": [ - "create_entity_type" - ] - }, - "DeleteEntityType": { - "methods": [ - "delete_entity_type" - ] - }, - "GetEntityType": { - "methods": [ - "get_entity_type" - ] - }, - "ListEntityTypes": { - "methods": [ - "list_entity_types" - ] - }, - "UpdateEntityType": { - "methods": [ - "update_entity_type" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EntityTypesAsyncClient", - "rpcs": { - "CreateEntityType": { - "methods": [ - "create_entity_type" - ] - }, - "DeleteEntityType": { - "methods": [ - "delete_entity_type" - ] - }, - "GetEntityType": { - "methods": [ - "get_entity_type" - ] - }, - "ListEntityTypes": { - "methods": [ - "list_entity_types" - ] - }, - "UpdateEntityType": { - "methods": [ - "update_entity_type" - ] - } - } - } - } - }, - "Environments": { - "clients": { - "grpc": { - "libraryClient": "EnvironmentsClient", - "rpcs": { - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListContinuousTestResults": { - "methods": [ - "list_continuous_test_results" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LookupEnvironmentHistory": { - "methods": [ - "lookup_environment_history" - ] - }, - "RunContinuousTest": { - "methods": [ - "run_continuous_test" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EnvironmentsAsyncClient", - "rpcs": { - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListContinuousTestResults": { - "methods": [ - "list_continuous_test_results" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LookupEnvironmentHistory": { - "methods": [ - "lookup_environment_history" - ] - }, - "RunContinuousTest": { - "methods": [ - "run_continuous_test" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - } - } - }, - "Experiments": { - "clients": { - "grpc": { - "libraryClient": "ExperimentsClient", - "rpcs": { - "CreateExperiment": { - "methods": [ - "create_experiment" - ] - }, - "DeleteExperiment": { - "methods": [ - "delete_experiment" - ] - }, - "GetExperiment": { - "methods": [ - "get_experiment" - ] - }, - "ListExperiments": { - "methods": [ - "list_experiments" - ] - }, - "StartExperiment": { - "methods": [ - "start_experiment" - ] - }, - "StopExperiment": { - "methods": [ - "stop_experiment" - ] - }, - "UpdateExperiment": { - "methods": [ - "update_experiment" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ExperimentsAsyncClient", - "rpcs": { - "CreateExperiment": { - "methods": [ - "create_experiment" - ] - }, - "DeleteExperiment": { - "methods": [ - "delete_experiment" - ] - }, - "GetExperiment": { - "methods": [ - "get_experiment" - ] - }, - "ListExperiments": { - "methods": [ - "list_experiments" - ] - }, - "StartExperiment": { - "methods": [ - "start_experiment" - ] - }, - "StopExperiment": { - "methods": [ - "stop_experiment" - ] - }, - "UpdateExperiment": { - "methods": [ - "update_experiment" - ] - } - } - } - } - }, - "Flows": { - "clients": { - "grpc": { - "libraryClient": "FlowsClient", - "rpcs": { - "CreateFlow": { - "methods": [ - "create_flow" - ] - }, - "DeleteFlow": { - "methods": [ - "delete_flow" - ] - }, - "ExportFlow": { - "methods": [ - "export_flow" - ] - }, - "GetFlow": { - "methods": [ - "get_flow" - ] - }, - "GetFlowValidationResult": { - "methods": [ - "get_flow_validation_result" - ] - }, - "ImportFlow": { - "methods": [ - "import_flow" - ] - }, - "ListFlows": { - "methods": [ - "list_flows" - ] - }, - "TrainFlow": { - "methods": [ - "train_flow" - ] - }, - "UpdateFlow": { - "methods": [ - "update_flow" - ] - }, - "ValidateFlow": { - "methods": [ - "validate_flow" - ] - } - } - }, - "grpc-async": { - "libraryClient": "FlowsAsyncClient", - "rpcs": { - "CreateFlow": { - "methods": [ - "create_flow" - ] - }, - "DeleteFlow": { - "methods": [ - "delete_flow" - ] - }, - "ExportFlow": { - "methods": [ - "export_flow" - ] - }, - "GetFlow": { - "methods": [ - "get_flow" - ] - }, - "GetFlowValidationResult": { - "methods": [ - "get_flow_validation_result" - ] - }, - "ImportFlow": { - "methods": [ - "import_flow" - ] - }, - "ListFlows": { - "methods": [ - "list_flows" - ] - }, - "TrainFlow": { - "methods": [ - "train_flow" - ] - }, - "UpdateFlow": { - "methods": [ - "update_flow" - ] - }, - "ValidateFlow": { - "methods": [ - "validate_flow" - ] - } - } - } - } - }, - "Intents": { - "clients": { - "grpc": { - "libraryClient": "IntentsClient", - "rpcs": { - "CreateIntent": { - "methods": [ - "create_intent" - ] - }, - "DeleteIntent": { - "methods": [ - "delete_intent" - ] - }, - "GetIntent": { - "methods": [ - "get_intent" - ] - }, - "ListIntents": { - "methods": [ - "list_intents" - ] - }, - "UpdateIntent": { - "methods": [ - "update_intent" - ] - } - } - }, - "grpc-async": { - "libraryClient": "IntentsAsyncClient", - "rpcs": { - "CreateIntent": { - "methods": [ - "create_intent" - ] - }, - "DeleteIntent": { - "methods": [ - "delete_intent" - ] - }, - "GetIntent": { - "methods": [ - "get_intent" - ] - }, - "ListIntents": { - "methods": [ - "list_intents" - ] - }, - "UpdateIntent": { - "methods": [ - "update_intent" - ] - } - } - } - } - }, - "Pages": { - "clients": { - "grpc": { - "libraryClient": "PagesClient", - "rpcs": { - "CreatePage": { - "methods": [ - "create_page" - ] - }, - "DeletePage": { - "methods": [ - "delete_page" - ] - }, - "GetPage": { - "methods": [ - "get_page" - ] - }, - "ListPages": { - "methods": [ - "list_pages" - ] - }, - "UpdatePage": { - "methods": [ - "update_page" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PagesAsyncClient", - "rpcs": { - "CreatePage": { - "methods": [ - "create_page" - ] - }, - "DeletePage": { - "methods": [ - "delete_page" - ] - }, - "GetPage": { - "methods": [ - "get_page" - ] - }, - "ListPages": { - "methods": [ - "list_pages" - ] - }, - "UpdatePage": { - "methods": [ - "update_page" - ] - } - } - } - } - }, - "SecuritySettingsService": { - "clients": { - "grpc": { - "libraryClient": "SecuritySettingsServiceClient", - "rpcs": { - "CreateSecuritySettings": { - "methods": [ - "create_security_settings" - ] - }, - "DeleteSecuritySettings": { - "methods": [ - "delete_security_settings" - ] - }, - "GetSecuritySettings": { - "methods": [ - "get_security_settings" - ] - }, - "ListSecuritySettings": { - "methods": [ - "list_security_settings" - ] - }, - "UpdateSecuritySettings": { - "methods": [ - "update_security_settings" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecuritySettingsServiceAsyncClient", - "rpcs": { - "CreateSecuritySettings": { - "methods": [ - "create_security_settings" - ] - }, - "DeleteSecuritySettings": { - "methods": [ - "delete_security_settings" - ] - }, - "GetSecuritySettings": { - "methods": [ - "get_security_settings" - ] - }, - "ListSecuritySettings": { - "methods": [ - "list_security_settings" - ] - }, - "UpdateSecuritySettings": { - "methods": [ - "update_security_settings" - ] - } - } - } - } - }, - "SessionEntityTypes": { - "clients": { - "grpc": { - "libraryClient": "SessionEntityTypesClient", - "rpcs": { - "CreateSessionEntityType": { - "methods": [ - "create_session_entity_type" - ] - }, - "DeleteSessionEntityType": { - "methods": [ - "delete_session_entity_type" - ] - }, - "GetSessionEntityType": { - "methods": [ - "get_session_entity_type" - ] - }, - "ListSessionEntityTypes": { - "methods": [ - "list_session_entity_types" - ] - }, - "UpdateSessionEntityType": { - "methods": [ - "update_session_entity_type" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SessionEntityTypesAsyncClient", - "rpcs": { - "CreateSessionEntityType": { - "methods": [ - "create_session_entity_type" - ] - }, - "DeleteSessionEntityType": { - "methods": [ - "delete_session_entity_type" - ] - }, - "GetSessionEntityType": { - "methods": [ - "get_session_entity_type" - ] - }, - "ListSessionEntityTypes": { - "methods": [ - "list_session_entity_types" - ] - }, - "UpdateSessionEntityType": { - "methods": [ - "update_session_entity_type" - ] - } - } - } - } - }, - "Sessions": { - "clients": { - "grpc": { - "libraryClient": "SessionsClient", - "rpcs": { - "DetectIntent": { - "methods": [ - "detect_intent" - ] - }, - "FulfillIntent": { - "methods": [ - "fulfill_intent" - ] - }, - "MatchIntent": { - "methods": [ - "match_intent" - ] - }, - "StreamingDetectIntent": { - "methods": [ - "streaming_detect_intent" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SessionsAsyncClient", - "rpcs": { - "DetectIntent": { - "methods": [ - "detect_intent" - ] - }, - "FulfillIntent": { - "methods": [ - "fulfill_intent" - ] - }, - "MatchIntent": { - "methods": [ - "match_intent" - ] - }, - "StreamingDetectIntent": { - "methods": [ - "streaming_detect_intent" - ] - } - } - } - } - }, - "TestCases": { - "clients": { - "grpc": { - "libraryClient": "TestCasesClient", - "rpcs": { - "BatchDeleteTestCases": { - "methods": [ - "batch_delete_test_cases" - ] - }, - "BatchRunTestCases": { - "methods": [ - "batch_run_test_cases" - ] - }, - "CalculateCoverage": { - "methods": [ - "calculate_coverage" - ] - }, - "CreateTestCase": { - "methods": [ - "create_test_case" - ] - }, - "ExportTestCases": { - "methods": [ - "export_test_cases" - ] - }, - "GetTestCase": { - "methods": [ - "get_test_case" - ] - }, - "GetTestCaseResult": { - "methods": [ - "get_test_case_result" - ] - }, - "ImportTestCases": { - "methods": [ - "import_test_cases" - ] - }, - "ListTestCaseResults": { - "methods": [ - "list_test_case_results" - ] - }, - "ListTestCases": { - "methods": [ - "list_test_cases" - ] - }, - "RunTestCase": { - "methods": [ - "run_test_case" - ] - }, - "UpdateTestCase": { - "methods": [ - "update_test_case" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TestCasesAsyncClient", - "rpcs": { - "BatchDeleteTestCases": { - "methods": [ - "batch_delete_test_cases" - ] - }, - "BatchRunTestCases": { - "methods": [ - "batch_run_test_cases" - ] - }, - "CalculateCoverage": { - "methods": [ - "calculate_coverage" - ] - }, - "CreateTestCase": { - "methods": [ - "create_test_case" - ] - }, - "ExportTestCases": { - "methods": [ - "export_test_cases" - ] - }, - "GetTestCase": { - "methods": [ - "get_test_case" - ] - }, - "GetTestCaseResult": { - "methods": [ - "get_test_case_result" - ] - }, - "ImportTestCases": { - "methods": [ - "import_test_cases" - ] - }, - "ListTestCaseResults": { - "methods": [ - "list_test_case_results" - ] - }, - "ListTestCases": { - "methods": [ - "list_test_cases" - ] - }, - "RunTestCase": { - "methods": [ - "run_test_case" - ] - }, - "UpdateTestCase": { - "methods": [ - "update_test_case" - ] - } - } - } - } - }, - "TransitionRouteGroups": { - "clients": { - "grpc": { - "libraryClient": "TransitionRouteGroupsClient", - "rpcs": { - "CreateTransitionRouteGroup": { - "methods": [ - "create_transition_route_group" - ] - }, - "DeleteTransitionRouteGroup": { - "methods": [ - "delete_transition_route_group" - ] - }, - "GetTransitionRouteGroup": { - "methods": [ - "get_transition_route_group" - ] - }, - "ListTransitionRouteGroups": { - "methods": [ - "list_transition_route_groups" - ] - }, - "UpdateTransitionRouteGroup": { - "methods": [ - "update_transition_route_group" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TransitionRouteGroupsAsyncClient", - "rpcs": { - "CreateTransitionRouteGroup": { - "methods": [ - "create_transition_route_group" - ] - }, - "DeleteTransitionRouteGroup": { - "methods": [ - "delete_transition_route_group" - ] - }, - "GetTransitionRouteGroup": { - "methods": [ - "get_transition_route_group" - ] - }, - "ListTransitionRouteGroups": { - "methods": [ - "list_transition_route_groups" - ] - }, - "UpdateTransitionRouteGroup": { - "methods": [ - "update_transition_route_group" - ] - } - } - } - } - }, - "Versions": { - "clients": { - "grpc": { - "libraryClient": "VersionsClient", - "rpcs": { - "CreateVersion": { - "methods": [ - "create_version" - ] - }, - "DeleteVersion": { - "methods": [ - "delete_version" - ] - }, - "GetVersion": { - "methods": [ - "get_version" - ] - }, - "ListVersions": { - "methods": [ - "list_versions" - ] - }, - "LoadVersion": { - "methods": [ - "load_version" - ] - }, - "UpdateVersion": { - "methods": [ - "update_version" - ] - } - } - }, - "grpc-async": { - "libraryClient": "VersionsAsyncClient", - "rpcs": { - "CreateVersion": { - "methods": [ - "create_version" - ] - }, - "DeleteVersion": { - "methods": [ - "delete_version" - ] - }, - "GetVersion": { - "methods": [ - "get_version" - ] - }, - "ListVersions": { - "methods": [ - "list_versions" - ] - }, - "LoadVersion": { - "methods": [ - "load_version" - ] - }, - "UpdateVersion": { - "methods": [ - "update_version" - ] - } - } - } - } - }, - "Webhooks": { - "clients": { - "grpc": { - "libraryClient": "WebhooksClient", - "rpcs": { - "CreateWebhook": { - "methods": [ - "create_webhook" - ] - }, - "DeleteWebhook": { - "methods": [ - "delete_webhook" - ] - }, - "GetWebhook": { - "methods": [ - "get_webhook" - ] - }, - "ListWebhooks": { - "methods": [ - "list_webhooks" - ] - }, - "UpdateWebhook": { - "methods": [ - "update_webhook" - ] - } - } - }, - "grpc-async": { - "libraryClient": "WebhooksAsyncClient", - "rpcs": { - "CreateWebhook": { - "methods": [ - "create_webhook" - ] - }, - "DeleteWebhook": { - "methods": [ - "delete_webhook" - ] - }, - "GetWebhook": { - "methods": [ - "get_webhook" - ] - }, - "ListWebhooks": { - "methods": [ - "list_webhooks" - ] - }, - "UpdateWebhook": { - "methods": [ - "update_webhook" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/py.typed b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/py.typed deleted file mode 100644 index 60fdca49..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-dialogflowcx package uses inline types. diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py deleted file mode 100644 index 057c8b80..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py deleted file mode 100644 index cf45251e..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py +++ /dev/null @@ -1,894 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.agents import pagers -from google.cloud.dialogflowcx_v3beta1.types import agent -from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent -from google.cloud.dialogflowcx_v3beta1.types import flow -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport -from .client import AgentsClient - - -class AgentsAsyncClient: - """Service for managing - [Agents][google.cloud.dialogflow.cx.v3beta1.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) - agent_validation_result_path = staticmethod(AgentsClient.agent_validation_result_path) - parse_agent_validation_result_path = staticmethod(AgentsClient.parse_agent_validation_result_path) - environment_path = staticmethod(AgentsClient.environment_path) - parse_environment_path = staticmethod(AgentsClient.parse_environment_path) - flow_path = staticmethod(AgentsClient.flow_path) - parse_flow_path = staticmethod(AgentsClient.parse_flow_path) - flow_validation_result_path = staticmethod(AgentsClient.flow_validation_result_path) - parse_flow_validation_result_path = staticmethod(AgentsClient.parse_flow_validation_result_path) - security_settings_path = staticmethod(AgentsClient.security_settings_path) - parse_security_settings_path = staticmethod(AgentsClient.parse_security_settings_path) - common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AgentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AgentsClient.common_folder_path) - parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) - common_organization_path = staticmethod(AgentsClient.common_organization_path) - parse_common_organization_path = staticmethod(AgentsClient.parse_common_organization_path) - common_project_path = staticmethod(AgentsClient.common_project_path) - parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) - common_location_path = staticmethod(AgentsClient.common_location_path) - parse_common_location_path = staticmethod(AgentsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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 list_agents(self, - request: agent.ListAgentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAgentsAsyncPager: - r"""Returns the list of all agents in the specified - location. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsRequest`): - The request object. The request message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. - parent (:class:`str`): - Required. The location to list all agents 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.dialogflowcx_v3beta1.services.agents.pagers.ListAgentsAsyncPager: - The response message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. - - 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.ListAgentsRequest(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_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.ListAgentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_agent(self, - request: agent.GetAgentRequest = None, - *, - name: 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.dialogflowcx_v3beta1.types.GetAgentRequest`): - The request object. The request message for - [Agents.GetAgent][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgent]. - name (:class:`str`): - Required. The name of the agent. Format: - ``projects//locations//agents/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3beta1.EntityType], - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = agent.GetAgentRequest(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_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(( - ("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_agent(self, - request: gcdc_agent.CreateAgentRequest = None, - *, - parent: str = None, - agent: gcdc_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_agent.Agent: - r"""Creates an agent in the specified location. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateAgentRequest`): - The request object. The request message for - [Agents.CreateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.CreateAgent]. - parent (:class:`str`): - Required. The location to create a agent for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - agent (:class:`google.cloud.dialogflowcx_v3beta1.types.Agent`): - Required. The agent to create. - 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.dialogflowcx_v3beta1.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3beta1.EntityType], - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 = gcdc_agent.CreateAgentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if agent is not None: - 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.create_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 update_agent(self, - request: gcdc_agent.UpdateAgentRequest = None, - *, - agent: gcdc_agent.Agent = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_agent.Agent: - r"""Updates the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateAgentRequest`): - The request object. The request message for - [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent]. - agent (:class:`google.cloud.dialogflowcx_v3beta1.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. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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.dialogflowcx_v3beta1.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3beta1.EntityType], - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, 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 = gcdc_agent.UpdateAgentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if agent is not None: - request.agent = agent - if update_mask is not None: - 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_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.name", request.agent.name), - )), - ) - - # 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, - *, - name: 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.dialogflowcx_v3beta1.types.DeleteAgentRequest`): - The request object. The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3beta1.Agents.DeleteAgent]. - name (:class:`str`): - Required. The name of the agent to delete. Format: - ``projects//locations//agents/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = agent.DeleteAgentRequest(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_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(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def export_agent(self, - request: agent.ExportAgentRequest = 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 binary file. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportAgentRequest`): - The request object. The request message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.ExportAgentResponse` - The response message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. - - """ - # Create or coerce a protobuf request object. - request = agent.ExportAgentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_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(( - ("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, - agent.ExportAgentResponse, - 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 binary file. - Replaces the current agent with a new one. Note that all - existing resources in agent (e.g. intents, entity types, - flows) will be removed. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest`): - The request object. The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3beta1.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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(( - ("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=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def validate_agent(self, - request: agent.ValidateAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.AgentValidationResult: - r"""Validates the specified agent and creates or updates - validation results. The agent in draft version is - validated. Please call this API after the training is - completed to get the complete validation results. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ValidateAgentRequest`): - The request object. The request message for - [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ValidateAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.AgentValidationResult: - The response message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. - - """ - # Create or coerce a protobuf request object. - request = agent.ValidateAgentRequest(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.validate_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(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_agent_validation_result(self, - request: agent.GetAgentValidationResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.AgentValidationResult: - r"""Gets the latest agent validation result. Agent - validation is performed when ValidateAgent is called. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetAgentValidationResultRequest`): - The request object. The request message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. - name (:class:`str`): - Required. The agent name. Format: - ``projects//locations//agents//validationResult``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.AgentValidationResult: - The response message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = agent.GetAgentValidationResultRequest(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_agent_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(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AgentsAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/client.py deleted file mode 100644 index 1418254c..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/client.py +++ /dev/null @@ -1,1129 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.agents import pagers -from google.cloud.dialogflowcx_v3beta1.types import agent -from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent -from google.cloud.dialogflowcx_v3beta1.types import flow -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AgentsGrpcTransport -from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport - - -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.cx.v3beta1.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,location: str,agent: str,) -> str: - """Returns a fully-qualified agent string.""" - return "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) - - @staticmethod - def parse_agent_path(path: str) -> Dict[str,str]: - """Parses a agent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def agent_validation_result_path(project: str,location: str,agent: str,) -> str: - """Returns a fully-qualified agent_validation_result string.""" - return "projects/{project}/locations/{location}/agents/{agent}/validationResult".format(project=project, location=location, agent=agent, ) - - @staticmethod - def parse_agent_validation_result_path(path: str) -> Dict[str,str]: - """Parses a agent_validation_result path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/validationResult$", path) - return m.groupdict() if m else {} - - @staticmethod - def environment_path(project: str,location: str,agent: str,environment: str,) -> str: - """Returns a fully-qualified environment string.""" - return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - - @staticmethod - def parse_environment_path(path: str) -> Dict[str,str]: - """Parses a environment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_validation_result_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow_validation_result string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_validation_result_path(path: str) -> Dict[str,str]: - """Parses a flow_validation_result path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_settings_path(project: str,location: str,security_settings: str,) -> str: - """Returns a fully-qualified security_settings string.""" - return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - - @staticmethod - def parse_security_settings_path(path: str) -> Dict[str,str]: - """Parses a security_settings path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def 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 list_agents(self, - request: agent.ListAgentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAgentsPager: - r"""Returns the list of all agents in the specified - location. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListAgentsRequest): - The request object. The request message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. - parent (str): - Required. The location to list all agents 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.dialogflowcx_v3beta1.services.agents.pagers.ListAgentsPager: - The response message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. - - 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.ListAgentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, agent.ListAgentsRequest): - request = agent.ListAgentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_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.ListAgentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_agent(self, - request: agent.GetAgentRequest = None, - *, - name: 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.dialogflowcx_v3beta1.types.GetAgentRequest): - The request object. The request message for - [Agents.GetAgent][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgent]. - name (str): - Required. The name of the agent. Format: - ``projects//locations//agents/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3beta1.EntityType], - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 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 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_agent] - - # Certain fields should be provided 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_agent(self, - request: gcdc_agent.CreateAgentRequest = None, - *, - parent: str = None, - agent: gcdc_agent.Agent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_agent.Agent: - r"""Creates an agent in the specified location. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateAgentRequest): - The request object. The request message for - [Agents.CreateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.CreateAgent]. - parent (str): - Required. The location to create a agent for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - agent (google.cloud.dialogflowcx_v3beta1.types.Agent): - Required. The agent to create. - 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.dialogflowcx_v3beta1.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3beta1.EntityType], - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, 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 gcdc_agent.CreateAgentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_agent.CreateAgentRequest): - request = gcdc_agent.CreateAgentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if agent is not None: - request.agent = agent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_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 update_agent(self, - request: gcdc_agent.UpdateAgentRequest = None, - *, - agent: gcdc_agent.Agent = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_agent.Agent: - r"""Updates the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateAgentRequest): - The request object. The request message for - [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent]. - agent (google.cloud.dialogflowcx_v3beta1.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. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.dialogflowcx_v3beta1.types.Agent: - Agents are best described as Natural Language Understanding (NLU) modules - that transform user requests into actionable data. - You can include agents in your app, product, or - service to determine user intent and respond to the - user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], - [Entity - Types][google.cloud.dialogflow.cx.v3beta1.EntityType], - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], - and so on to manage the conversation flows.. - - """ - # Create or coerce a protobuf request object. - # Sanity 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, 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 gcdc_agent.UpdateAgentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_agent.UpdateAgentRequest): - request = gcdc_agent.UpdateAgentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if agent is not None: - request.agent = agent - if update_mask is not None: - 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_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("agent.name", request.agent.name), - )), - ) - - # 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, - *, - name: 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.dialogflowcx_v3beta1.types.DeleteAgentRequest): - The request object. The request message for - [Agents.DeleteAgent][google.cloud.dialogflow.cx.v3beta1.Agents.DeleteAgent]. - name (str): - Required. The name of the agent to delete. Format: - ``projects//locations//agents/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 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 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_agent] - - # Certain fields should be 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 export_agent(self, - request: agent.ExportAgentRequest = 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 binary file. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ExportAgentRequest): - The request object. The request message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.ExportAgentResponse` - The response message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a agent.ExportAgentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, agent.ExportAgentRequest): - request = agent.ExportAgentRequest(request) - - # 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(( - ("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, - agent.ExportAgentResponse, - 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 binary file. - Replaces the current agent with a new one. Note that all - existing resources in agent (e.g. intents, entity types, - flows) will be removed. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest): - The request object. The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3beta1.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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(( - ("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=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def validate_agent(self, - request: agent.ValidateAgentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.AgentValidationResult: - r"""Validates the specified agent and creates or updates - validation results. The agent in draft version is - validated. Please call this API after the training is - completed to get the complete validation results. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ValidateAgentRequest): - The request object. The request message for - [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ValidateAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.AgentValidationResult: - The response message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a agent.ValidateAgentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, agent.ValidateAgentRequest): - request = agent.ValidateAgentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_agent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_agent_validation_result(self, - request: agent.GetAgentValidationResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> agent.AgentValidationResult: - r"""Gets the latest agent validation result. Agent - validation is performed when ValidateAgent is called. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetAgentValidationResultRequest): - The request object. The request message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. - name (str): - Required. The agent name. Format: - ``projects//locations//agents//validationResult``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.AgentValidationResult: - The response message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 agent.GetAgentValidationResultRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, agent.GetAgentValidationResultRequest): - request = agent.GetAgentValidationResultRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_agent_validation_result] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AgentsClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py deleted file mode 100644 index 2a032cb9..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.types import agent - - -class ListAgentsPager: - """A pager for iterating through ``list_agents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``agents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAgents`` requests and continue to iterate - through the ``agents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse` - 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.ListAgentsResponse], - request: agent.ListAgentsRequest, - response: agent.ListAgentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListAgentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse): - 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.ListAgentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[agent.ListAgentsResponse]: - 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 ListAgentsAsyncPager: - """A pager for iterating through ``list_agents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``agents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAgents`` requests and continue to iterate - through the ``agents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse` - 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.ListAgentsResponse]], - request: agent.ListAgentsRequest, - response: agent.ListAgentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListAgentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListAgentsResponse): - 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.ListAgentsRequest(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.ListAgentsResponse]: - 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py deleted file mode 100644 index 0dc0c06c..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py deleted file mode 100644 index bf1db172..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.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 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.dialogflowcx_v3beta1.types import agent -from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent -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-dialogflowcx', - ).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.list_agents: gapic_v1.method.wrap_method( - self.list_agents, - default_timeout=None, - client_info=client_info, - ), - self.get_agent: gapic_v1.method.wrap_method( - self.get_agent, - default_timeout=None, - client_info=client_info, - ), - self.create_agent: gapic_v1.method.wrap_method( - self.create_agent, - default_timeout=None, - client_info=client_info, - ), - self.update_agent: gapic_v1.method.wrap_method( - self.update_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.export_agent: gapic_v1.method.wrap_method( - self.export_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.validate_agent: gapic_v1.method.wrap_method( - self.validate_agent, - default_timeout=None, - client_info=client_info, - ), - self.get_agent_validation_result: gapic_v1.method.wrap_method( - self.get_agent_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 list_agents(self) -> Callable[ - [agent.ListAgentsRequest], - Union[ - agent.ListAgentsResponse, - Awaitable[agent.ListAgentsResponse] - ]]: - raise NotImplementedError() - - @property - def get_agent(self) -> Callable[ - [agent.GetAgentRequest], - Union[ - agent.Agent, - Awaitable[agent.Agent] - ]]: - raise NotImplementedError() - - @property - def create_agent(self) -> Callable[ - [gcdc_agent.CreateAgentRequest], - Union[ - gcdc_agent.Agent, - Awaitable[gcdc_agent.Agent] - ]]: - raise NotImplementedError() - - @property - def update_agent(self) -> Callable[ - [gcdc_agent.UpdateAgentRequest], - Union[ - gcdc_agent.Agent, - Awaitable[gcdc_agent.Agent] - ]]: - raise NotImplementedError() - - @property - def delete_agent(self) -> Callable[ - [agent.DeleteAgentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def export_agent(self) -> Callable[ - [agent.ExportAgentRequest], - 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 validate_agent(self) -> Callable[ - [agent.ValidateAgentRequest], - Union[ - agent.AgentValidationResult, - Awaitable[agent.AgentValidationResult] - ]]: - raise NotImplementedError() - - @property - def get_agent_validation_result(self) -> Callable[ - [agent.GetAgentValidationResultRequest], - Union[ - agent.AgentValidationResult, - Awaitable[agent.AgentValidationResult] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'AgentsTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py deleted file mode 100644 index 4c79b5c3..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py +++ /dev/null @@ -1,486 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import agent -from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent -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.cx.v3beta1.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 list_agents(self) -> Callable[ - [agent.ListAgentsRequest], - agent.ListAgentsResponse]: - r"""Return a callable for the list agents method over gRPC. - - Returns the list of all agents in the specified - location. - - Returns: - Callable[[~.ListAgentsRequest], - ~.ListAgentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_agents' not in self._stubs: - self._stubs['list_agents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Agents/ListAgents', - request_serializer=agent.ListAgentsRequest.serialize, - response_deserializer=agent.ListAgentsResponse.deserialize, - ) - return self._stubs['list_agents'] - - @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.cx.v3beta1.Agents/GetAgent', - request_serializer=agent.GetAgentRequest.serialize, - response_deserializer=agent.Agent.deserialize, - ) - return self._stubs['get_agent'] - - @property - def create_agent(self) -> Callable[ - [gcdc_agent.CreateAgentRequest], - gcdc_agent.Agent]: - r"""Return a callable for the create agent method over gRPC. - - Creates an agent in the specified location. - - Returns: - Callable[[~.CreateAgentRequest], - ~.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 'create_agent' not in self._stubs: - self._stubs['create_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Agents/CreateAgent', - request_serializer=gcdc_agent.CreateAgentRequest.serialize, - response_deserializer=gcdc_agent.Agent.deserialize, - ) - return self._stubs['create_agent'] - - @property - def update_agent(self) -> Callable[ - [gcdc_agent.UpdateAgentRequest], - gcdc_agent.Agent]: - r"""Return a callable for the update agent method over gRPC. - - Updates the specified agent. - - Returns: - Callable[[~.UpdateAgentRequest], - ~.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 'update_agent' not in self._stubs: - self._stubs['update_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Agents/UpdateAgent', - request_serializer=gcdc_agent.UpdateAgentRequest.serialize, - response_deserializer=gcdc_agent.Agent.deserialize, - ) - return self._stubs['update_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.cx.v3beta1.Agents/DeleteAgent', - request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_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 binary file. - - 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.cx.v3beta1.Agents/ExportAgent', - request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_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 binary file. - Replaces the current agent with a new one. Note that all - existing resources in agent (e.g. intents, entity types, - flows) will be removed. - - 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.cx.v3beta1.Agents/RestoreAgent', - request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['restore_agent'] - - @property - def validate_agent(self) -> Callable[ - [agent.ValidateAgentRequest], - agent.AgentValidationResult]: - r"""Return a callable for the validate agent method over gRPC. - - Validates the specified agent and creates or updates - validation results. The agent in draft version is - validated. Please call this API after the training is - completed to get the complete validation results. - - Returns: - Callable[[~.ValidateAgentRequest], - ~.AgentValidationResult]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_agent' not in self._stubs: - self._stubs['validate_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Agents/ValidateAgent', - request_serializer=agent.ValidateAgentRequest.serialize, - response_deserializer=agent.AgentValidationResult.deserialize, - ) - return self._stubs['validate_agent'] - - @property - def get_agent_validation_result(self) -> Callable[ - [agent.GetAgentValidationResultRequest], - agent.AgentValidationResult]: - r"""Return a callable for the get agent validation result method over gRPC. - - Gets the latest agent validation result. Agent - validation is performed when ValidateAgent is called. - - Returns: - Callable[[~.GetAgentValidationResultRequest], - ~.AgentValidationResult]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_validation_result' not in self._stubs: - self._stubs['get_agent_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Agents/GetAgentValidationResult', - request_serializer=agent.GetAgentValidationResultRequest.serialize, - response_deserializer=agent.AgentValidationResult.deserialize, - ) - return self._stubs['get_agent_validation_result'] - - -__all__ = ( - 'AgentsGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py deleted file mode 100644 index 594f44a3..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py +++ /dev/null @@ -1,490 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import agent -from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent -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.cx.v3beta1.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 list_agents(self) -> Callable[ - [agent.ListAgentsRequest], - Awaitable[agent.ListAgentsResponse]]: - r"""Return a callable for the list agents method over gRPC. - - Returns the list of all agents in the specified - location. - - Returns: - Callable[[~.ListAgentsRequest], - Awaitable[~.ListAgentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_agents' not in self._stubs: - self._stubs['list_agents'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Agents/ListAgents', - request_serializer=agent.ListAgentsRequest.serialize, - response_deserializer=agent.ListAgentsResponse.deserialize, - ) - return self._stubs['list_agents'] - - @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.cx.v3beta1.Agents/GetAgent', - request_serializer=agent.GetAgentRequest.serialize, - response_deserializer=agent.Agent.deserialize, - ) - return self._stubs['get_agent'] - - @property - def create_agent(self) -> Callable[ - [gcdc_agent.CreateAgentRequest], - Awaitable[gcdc_agent.Agent]]: - r"""Return a callable for the create agent method over gRPC. - - Creates an agent in the specified location. - - Returns: - Callable[[~.CreateAgentRequest], - 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 'create_agent' not in self._stubs: - self._stubs['create_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Agents/CreateAgent', - request_serializer=gcdc_agent.CreateAgentRequest.serialize, - response_deserializer=gcdc_agent.Agent.deserialize, - ) - return self._stubs['create_agent'] - - @property - def update_agent(self) -> Callable[ - [gcdc_agent.UpdateAgentRequest], - Awaitable[gcdc_agent.Agent]]: - r"""Return a callable for the update agent method over gRPC. - - Updates the specified agent. - - Returns: - Callable[[~.UpdateAgentRequest], - 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 'update_agent' not in self._stubs: - self._stubs['update_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Agents/UpdateAgent', - request_serializer=gcdc_agent.UpdateAgentRequest.serialize, - response_deserializer=gcdc_agent.Agent.deserialize, - ) - return self._stubs['update_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.cx.v3beta1.Agents/DeleteAgent', - request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_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 binary file. - - 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.cx.v3beta1.Agents/ExportAgent', - request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_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 binary file. - Replaces the current agent with a new one. Note that all - existing resources in agent (e.g. intents, entity types, - flows) will be removed. - - 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.cx.v3beta1.Agents/RestoreAgent', - request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['restore_agent'] - - @property - def validate_agent(self) -> Callable[ - [agent.ValidateAgentRequest], - Awaitable[agent.AgentValidationResult]]: - r"""Return a callable for the validate agent method over gRPC. - - Validates the specified agent and creates or updates - validation results. The agent in draft version is - validated. Please call this API after the training is - completed to get the complete validation results. - - Returns: - Callable[[~.ValidateAgentRequest], - Awaitable[~.AgentValidationResult]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_agent' not in self._stubs: - self._stubs['validate_agent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Agents/ValidateAgent', - request_serializer=agent.ValidateAgentRequest.serialize, - response_deserializer=agent.AgentValidationResult.deserialize, - ) - return self._stubs['validate_agent'] - - @property - def get_agent_validation_result(self) -> Callable[ - [agent.GetAgentValidationResultRequest], - Awaitable[agent.AgentValidationResult]]: - r"""Return a callable for the get agent validation result method over gRPC. - - Gets the latest agent validation result. Agent - validation is performed when ValidateAgent is called. - - Returns: - Callable[[~.GetAgentValidationResultRequest], - Awaitable[~.AgentValidationResult]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly 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_validation_result' not in self._stubs: - self._stubs['get_agent_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Agents/GetAgentValidationResult', - request_serializer=agent.GetAgentValidationResultRequest.serialize, - response_deserializer=agent.AgentValidationResult.deserialize, - ) - return self._stubs['get_agent_validation_result'] - - -__all__ = ( - 'AgentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py deleted file mode 100644 index 82dfe86f..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py deleted file mode 100644 index 66393794..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py +++ /dev/null @@ -1,659 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.entity_types import pagers -from google.cloud.dialogflowcx_v3beta1.types import entity_type -from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type -from google.protobuf import field_mask_pb2 # 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.cx.v3beta1.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, - 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.dialogflowcx_v3beta1.types.ListEntityTypesRequest`): - The request object. The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.EntityTypes.ListEntityTypes]. - parent (:class:`str`): - Required. The agent to list all entity types for. - Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.entity_types.pagers.ListEntityTypesAsyncPager: - The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.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]) - if request is not 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 - - # 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, - 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.dialogflowcx_v3beta1.types.GetEntityTypeRequest`): - The request object. The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.GetEntityType]. - name (:class:`str`): - Required. The name of the entity type. Format: - ``projects//locations//agents//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. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not 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 - - # 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: gcdc_entity_type.CreateEntityTypeRequest = None, - *, - parent: str = None, - entity_type: gcdc_entity_type.EntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateEntityTypeRequest`): - The request object. The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.CreateEntityType]. - parent (:class:`str`): - Required. The agent to create a entity type for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_type (:class:`google.cloud.dialogflowcx_v3beta1.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. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_entity_type.CreateEntityTypeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entity_type is not None: - request.entity_type = 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_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: gcdc_entity_type.UpdateEntityTypeRequest = None, - *, - entity_type: gcdc_entity_type.EntityType = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_entity_type.EntityType: - r"""Updates the specified entity type. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateEntityTypeRequest`): - The request object. The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.UpdateEntityType]. - entity_type (:class:`google.cloud.dialogflowcx_v3beta1.types.EntityType`): - 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. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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.dialogflowcx_v3beta1.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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, 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 = gcdc_entity_type.UpdateEntityTypeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entity_type is not None: - request.entity_type = entity_type - if update_mask is not None: - 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.dialogflowcx_v3beta1.types.DeleteEntityTypeRequest`): - The request object. The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.DeleteEntityType]. - name (:class:`str`): - Required. The name of the entity type to delete. Format: - ``projects//locations//agents//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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "EntityTypesAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py deleted file mode 100644 index 7b237697..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py +++ /dev/null @@ -1,846 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.entity_types import pagers -from google.cloud.dialogflowcx_v3beta1.types import entity_type -from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type -from google.protobuf import field_mask_pb2 # 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.cx.v3beta1.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,location: str,agent: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?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, 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, - 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.dialogflowcx_v3beta1.types.ListEntityTypesRequest): - The request object. The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.EntityTypes.ListEntityTypes]. - parent (str): - Required. The agent to list all entity types for. - Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.entity_types.pagers.ListEntityTypesPager: - The response message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is 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 - - # 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, - 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.dialogflowcx_v3beta1.types.GetEntityTypeRequest): - The request object. The request message for - [EntityTypes.GetEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.GetEntityType]. - name (str): - Required. The name of the entity type. Format: - ``projects//locations//agents//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. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is 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 - - # 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: gcdc_entity_type.CreateEntityTypeRequest = None, - *, - parent: str = None, - entity_type: gcdc_entity_type.EntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_entity_type.EntityType: - r"""Creates an entity type in the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateEntityTypeRequest): - The request object. The request message for - [EntityTypes.CreateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.CreateEntityType]. - parent (str): - Required. The agent to create a entity type for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - entity_type (google.cloud.dialogflowcx_v3beta1.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. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_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, gcdc_entity_type.CreateEntityTypeRequest): - request = gcdc_entity_type.CreateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if entity_type is not None: - request.entity_type = entity_type - - # 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: gcdc_entity_type.UpdateEntityTypeRequest = None, - *, - entity_type: gcdc_entity_type.EntityType = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_entity_type.EntityType: - r"""Updates the specified entity type. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateEntityTypeRequest): - The request object. The request message for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.UpdateEntityType]. - entity_type (google.cloud.dialogflowcx_v3beta1.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. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.dialogflowcx_v3beta1.types.EntityType: - Entities are extracted from user input and represent parameters that are - meaningful to your application. For example, a date - range, a proper name such as a geographic location or - landmark, and so on. Entities represent actionable - data for your application. - - When you define an entity, you can also include - synonyms that all map to that entity. For example, - "soft drink", "soda", "pop", and so on. - - There are three types of entities: - - - **System** - entities that are defined by the - Dialogflow API for common data types such as date, - time, currency, and so on. A system entity is - represented by the EntityType type. - - **Custom** - entities that are defined by you that - represent actionable data that is meaningful to - your application. For example, you could define a - pizza.sauce entity for red or white pizza sauce, a - pizza.cheese entity for the different types of - cheese on a pizza, a pizza.topping entity for - different toppings, and so on. A custom entity is - represented by the EntityType type. - - **User** - entities that are built for an - individual user such as favorites, preferences, - playlists, and so on. A user entity is represented - by the - [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] - type. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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, 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 gcdc_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, gcdc_entity_type.UpdateEntityTypeRequest): - request = gcdc_entity_type.UpdateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if entity_type is not None: - request.entity_type = entity_type - if update_mask is not None: - 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.dialogflowcx_v3beta1.types.DeleteEntityTypeRequest): - The request object. The request message for - [EntityTypes.DeleteEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.DeleteEntityType]. - name (str): - Required. The name of the entity type to delete. Format: - ``projects//locations//agents//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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "EntityTypesClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py deleted file mode 100644 index 77181a32..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.types import entity_type - - -class ListEntityTypesPager: - """A pager for iterating through ``list_entity_types`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py deleted file mode 100644 index 1a2aa82d..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py deleted file mode 100644 index 5402dcfe..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/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.dialogflowcx_v3beta1.types import entity_type -from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflowcx', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -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, - ), - } - - @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[ - [gcdc_entity_type.CreateEntityTypeRequest], - Union[ - gcdc_entity_type.EntityType, - Awaitable[gcdc_entity_type.EntityType] - ]]: - raise NotImplementedError() - - @property - def update_entity_type(self) -> Callable[ - [gcdc_entity_type.UpdateEntityTypeRequest], - Union[ - gcdc_entity_type.EntityType, - Awaitable[gcdc_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() - - -__all__ = ( - 'EntityTypesTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py deleted file mode 100644 index f56c3376..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/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.dialogflowcx_v3beta1.types import entity_type -from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 # type: ignore -from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO - - -class EntityTypesGrpcTransport(EntityTypesTransport): - """gRPC backend transport for EntityTypes. - - Service for managing - [EntityTypes][google.cloud.dialogflow.cx.v3beta1.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] = {} - - 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_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.cx.v3beta1.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.cx.v3beta1.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[ - [gcdc_entity_type.CreateEntityTypeRequest], - gcdc_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.cx.v3beta1.EntityTypes/CreateEntityType', - request_serializer=gcdc_entity_type.CreateEntityTypeRequest.serialize, - response_deserializer=gcdc_entity_type.EntityType.deserialize, - ) - return self._stubs['create_entity_type'] - - @property - def update_entity_type(self) -> Callable[ - [gcdc_entity_type.UpdateEntityTypeRequest], - gcdc_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.cx.v3beta1.EntityTypes/UpdateEntityType', - request_serializer=gcdc_entity_type.UpdateEntityTypeRequest.serialize, - response_deserializer=gcdc_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.cx.v3beta1.EntityTypes/DeleteEntityType', - request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entity_type'] - - -__all__ = ( - 'EntityTypesGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc_asyncio.py deleted file mode 100644 index 6352fc58..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/entity_types/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.dialogflowcx_v3beta1.types import entity_type -from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 # 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.cx.v3beta1.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] = {} - - 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_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.cx.v3beta1.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.cx.v3beta1.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[ - [gcdc_entity_type.CreateEntityTypeRequest], - Awaitable[gcdc_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.cx.v3beta1.EntityTypes/CreateEntityType', - request_serializer=gcdc_entity_type.CreateEntityTypeRequest.serialize, - response_deserializer=gcdc_entity_type.EntityType.deserialize, - ) - return self._stubs['create_entity_type'] - - @property - def update_entity_type(self) -> Callable[ - [gcdc_entity_type.UpdateEntityTypeRequest], - Awaitable[gcdc_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.cx.v3beta1.EntityTypes/UpdateEntityType', - request_serializer=gcdc_entity_type.UpdateEntityTypeRequest.serialize, - response_deserializer=gcdc_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.cx.v3beta1.EntityTypes/DeleteEntityType', - request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_entity_type'] - - -__all__ = ( - 'EntityTypesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py deleted file mode 100644 index a3ad29ec..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py deleted file mode 100644 index 3726bf8b..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py +++ /dev/null @@ -1,883 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.environments import pagers -from google.cloud.dialogflowcx_v3beta1.types import environment -from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .client import EnvironmentsClient - - -class EnvironmentsAsyncClient: - """Service for managing - [Environments][google.cloud.dialogflow.cx.v3beta1.Environment]. - """ - - _client: EnvironmentsClient - - DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - - continuous_test_result_path = staticmethod(EnvironmentsClient.continuous_test_result_path) - parse_continuous_test_result_path = staticmethod(EnvironmentsClient.parse_continuous_test_result_path) - environment_path = staticmethod(EnvironmentsClient.environment_path) - parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) - test_case_result_path = staticmethod(EnvironmentsClient.test_case_result_path) - parse_test_case_result_path = staticmethod(EnvironmentsClient.parse_test_case_result_path) - version_path = staticmethod(EnvironmentsClient.version_path) - parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) - common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) - parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) - common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) - parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) - common_project_path = staticmethod(EnvironmentsClient.common_project_path) - parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) - common_location_path = staticmethod(EnvironmentsClient.common_location_path) - parse_common_location_path = staticmethod(EnvironmentsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @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 environments in the specified - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListEnvironmentsRequest`): - The request object. The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.Environments.ListEnvironments]. - parent (:class:`str`): - Required. The - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to - list all environments for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.environments.pagers.ListEnvironmentsAsyncPager: - The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.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, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetEnvironmentRequest`): - The request object. The request message for - [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.GetEnvironment]. - name (:class:`str`): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Environment: - Represents an environment for an - agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = environment.GetEnvironmentRequest(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_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: gcdc_environment.CreateEnvironmentRequest = None, - *, - parent: str = None, - environment: gcdc_environment.Environment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates an - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in - the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateEnvironmentRequest`): - The request object. The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.CreateEnvironment]. - parent (:class:`str`): - Required. The - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to - create an - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (:class:`google.cloud.dialogflowcx_v3beta1.types.Environment`): - Required. The environment to create. - This corresponds to the ``environment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflowcx_v3beta1.types.Environment` Represents an environment for an agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, environment]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_environment.CreateEnvironmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if environment is not None: - request.environment = environment - - # 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcdc_environment.Environment, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def update_environment(self, - request: gcdc_environment.UpdateEnvironmentRequest = None, - *, - environment: gcdc_environment.Environment = 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 - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateEnvironmentRequest`): - The request object. The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.UpdateEnvironment]. - environment (:class:`google.cloud.dialogflowcx_v3beta1.types.Environment`): - Required. The environment to update. - This corresponds to the ``environment`` 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflowcx_v3beta1.types.Environment` Represents an environment for an agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([environment, 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 = gcdc_environment.UpdateEnvironmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if environment is not None: - request.environment = environment - if update_mask is not None: - 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_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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcdc_environment.Environment, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def delete_environment(self, - request: environment.DeleteEnvironmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteEnvironmentRequest`): - The request object. The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.DeleteEnvironment]. - name (:class:`str`): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - to delete. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = environment.DeleteEnvironmentRequest(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_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 lookup_environment_history(self, - request: environment.LookupEnvironmentHistoryRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.LookupEnvironmentHistoryAsyncPager: - r"""Looks up the history of the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryRequest`): - The request object. The request message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. - name (:class:`str`): - Required. Resource name of the environment to look up - the history for. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.environments.pagers.LookupEnvironmentHistoryAsyncPager: - The response message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. - - 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([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 = environment.LookupEnvironmentHistoryRequest(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.lookup_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(( - ("name", request.name), - )), - ) - - # 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.LookupEnvironmentHistoryAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_continuous_test(self, - request: environment.RunContinuousTestRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Kicks off a continuous test under the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestRequest`): - The request object. The request message for - [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestResponse` - The response message for - [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. - - """ - # Create or coerce a protobuf request object. - request = environment.RunContinuousTestRequest(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.run_continuous_test, - default_timeout=None, - client_info=DEFAULT_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", request.environment), - )), - ) - - # 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, - environment.RunContinuousTestResponse, - metadata_type=environment.RunContinuousTestMetadata, - ) - - # Done; return the response. - return response - - async def list_continuous_test_results(self, - request: environment.ListContinuousTestResultsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListContinuousTestResultsAsyncPager: - r"""Fetches a list of continuous test results for a given - environment. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest`): - The request object. The request message for - [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3beta1.Environments.ListContinuousTestResults]. - parent (:class:`str`): - Required. The environment to list results for. Format: - ``projects//locations//agents// 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.environments.pagers.ListContinuousTestResultsAsyncPager: - The response message for - [Environments.ListTestCaseResults][]. - - 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.ListContinuousTestResultsRequest(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_continuous_test_results, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListContinuousTestResultsAsyncPager( - 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "EnvironmentsAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/client.py deleted file mode 100644 index 4110792f..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/client.py +++ /dev/null @@ -1,1098 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.environments import pagers -from google.cloud.dialogflowcx_v3beta1.types import environment -from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EnvironmentsGrpcTransport -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport - - -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.cx.v3beta1.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 continuous_test_result_path(project: str,location: str,agent: str,environment: str,continuous_test_result: str,) -> str: - """Returns a fully-qualified continuous_test_result string.""" - return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/continuousTestResults/{continuous_test_result}".format(project=project, location=location, agent=agent, environment=environment, continuous_test_result=continuous_test_result, ) - - @staticmethod - def parse_continuous_test_result_path(path: str) -> Dict[str,str]: - """Parses a continuous_test_result path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/continuousTestResults/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def environment_path(project: str,location: str,agent: str,environment: str,) -> str: - """Returns a fully-qualified environment string.""" - return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - - @staticmethod - def parse_environment_path(path: str) -> Dict[str,str]: - """Parses a environment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def test_case_result_path(project: str,location: str,agent: str,test_case: str,result: str,) -> str: - """Returns a fully-qualified test_case_result string.""" - return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) - - @staticmethod - def parse_test_case_result_path(path: str) -> Dict[str,str]: - """Parses a test_case_result path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: - """Returns a fully-qualified version string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - - @staticmethod - def parse_version_path(path: str) -> Dict[str,str]: - """Parses a version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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, 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 environments in the specified - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListEnvironmentsRequest): - The request object. The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.Environments.ListEnvironments]. - parent (str): - Required. The - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to - list all environments for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.environments.pagers.ListEnvironmentsPager: - The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.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, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> environment.Environment: - r"""Retrieves the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetEnvironmentRequest): - The request object. The request message for - [Environments.GetEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.GetEnvironment]. - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Environment: - Represents an environment for an - agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 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) - # 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_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: gcdc_environment.CreateEnvironmentRequest = None, - *, - parent: str = None, - environment: gcdc_environment.Environment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates an - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in - the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateEnvironmentRequest): - The request object. The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.CreateEnvironment]. - parent (str): - Required. The - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to - create an - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (google.cloud.dialogflowcx_v3beta1.types.Environment): - Required. The environment to create. - This corresponds to the ``environment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflowcx_v3beta1.types.Environment` Represents an environment for an agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, environment]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_environment.CreateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_environment.CreateEnvironmentRequest): - request = gcdc_environment.CreateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if environment is not None: - request.environment = environment - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcdc_environment.Environment, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def update_environment(self, - request: gcdc_environment.UpdateEnvironmentRequest = None, - *, - environment: gcdc_environment.Environment = 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 - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateEnvironmentRequest): - The request object. The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.UpdateEnvironment]. - environment (google.cloud.dialogflowcx_v3beta1.types.Environment): - Required. The environment to update. - This corresponds to the ``environment`` 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.dialogflowcx_v3beta1.types.Environment` Represents an environment for an agent. 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. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([environment, 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 gcdc_environment.UpdateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_environment.UpdateEnvironmentRequest): - request = gcdc_environment.UpdateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if environment is not None: - request.environment = environment - if update_mask is not None: - 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_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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcdc_environment.Environment, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def delete_environment(self, - request: environment.DeleteEnvironmentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.DeleteEnvironmentRequest): - The request object. The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.DeleteEnvironment]. - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - to delete. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 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) - # 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_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 lookup_environment_history(self, - request: environment.LookupEnvironmentHistoryRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.LookupEnvironmentHistoryPager: - r"""Looks up the history of the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryRequest): - The request object. The request message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. - name (str): - Required. Resource name of the environment to look up - the history for. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.environments.pagers.LookupEnvironmentHistoryPager: - The response message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. - - 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([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 environment.LookupEnvironmentHistoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.LookupEnvironmentHistoryRequest): - request = environment.LookupEnvironmentHistoryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.lookup_environment_history] - - # Certain fields should be provided 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, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.LookupEnvironmentHistoryPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_continuous_test(self, - request: environment.RunContinuousTestRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Kicks off a continuous test under the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestRequest): - The request object. The request message for - [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.RunContinuousTestResponse` - The response message for - [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a environment.RunContinuousTestRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.RunContinuousTestRequest): - request = environment.RunContinuousTestRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_continuous_test] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environment.RunContinuousTestResponse, - metadata_type=environment.RunContinuousTestMetadata, - ) - - # Done; return the response. - return response - - def list_continuous_test_results(self, - request: environment.ListContinuousTestResultsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListContinuousTestResultsPager: - r"""Fetches a list of continuous test results for a given - environment. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest): - The request object. The request message for - [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3beta1.Environments.ListContinuousTestResults]. - parent (str): - Required. The environment to list results for. Format: - ``projects//locations//agents// 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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.environments.pagers.ListContinuousTestResultsPager: - The response message for - [Environments.ListTestCaseResults][]. - - 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.ListContinuousTestResultsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, environment.ListContinuousTestResultsRequest): - request = environment.ListContinuousTestResultsRequest(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_continuous_test_results] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListContinuousTestResultsPager( - 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "EnvironmentsClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py deleted file mode 100644 index d7df3198..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.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. -# -from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.dialogflowcx_v3beta1.types import environment - - -class ListEnvironmentsPager: - """A pager for iterating through ``list_environments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.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 LookupEnvironmentHistoryPager: - """A pager for iterating through ``lookup_environment_history`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse` object, and - provides an ``__iter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``LookupEnvironmentHistory`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse` - 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.LookupEnvironmentHistoryResponse], - request: environment.LookupEnvironmentHistoryRequest, - response: environment.LookupEnvironmentHistoryResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse): - 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.LookupEnvironmentHistoryRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[environment.LookupEnvironmentHistoryResponse]: - 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 LookupEnvironmentHistoryAsyncPager: - """A pager for iterating through ``lookup_environment_history`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``LookupEnvironmentHistory`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse` - 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.LookupEnvironmentHistoryResponse]], - request: environment.LookupEnvironmentHistoryRequest, - response: environment.LookupEnvironmentHistoryResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.LookupEnvironmentHistoryResponse): - 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.LookupEnvironmentHistoryRequest(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.LookupEnvironmentHistoryResponse]: - 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 ListContinuousTestResultsPager: - """A pager for iterating through ``list_continuous_test_results`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``continuous_test_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListContinuousTestResults`` requests and continue to iterate - through the ``continuous_test_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` - 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.ListContinuousTestResultsResponse], - request: environment.ListContinuousTestResultsRequest, - response: environment.ListContinuousTestResultsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse): - 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.ListContinuousTestResultsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[environment.ListContinuousTestResultsResponse]: - 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.ContinuousTestResult]: - for page in self.pages: - yield from page.continuous_test_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListContinuousTestResultsAsyncPager: - """A pager for iterating through ``list_continuous_test_results`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``continuous_test_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListContinuousTestResults`` requests and continue to iterate - through the ``continuous_test_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse` - 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.ListContinuousTestResultsResponse]], - request: environment.ListContinuousTestResultsRequest, - response: environment.ListContinuousTestResultsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListContinuousTestResultsResponse): - 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.ListContinuousTestResultsRequest(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.ListContinuousTestResultsResponse]: - 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.ContinuousTestResult]: - async def async_generator(): - async for page in self.pages: - for response in page.continuous_test_results: - 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py deleted file mode 100644 index fac90efe..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py deleted file mode 100644 index 902dd17d..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py +++ /dev/null @@ -1,290 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import environment -from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment -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-dialogflowcx', - ).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.lookup_environment_history: gapic_v1.method.wrap_method( - self.lookup_environment_history, - default_timeout=None, - client_info=client_info, - ), - self.run_continuous_test: gapic_v1.method.wrap_method( - self.run_continuous_test, - default_timeout=None, - client_info=client_info, - ), - self.list_continuous_test_results: gapic_v1.method.wrap_method( - self.list_continuous_test_results, - 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_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[ - [gcdc_environment.CreateEnvironmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_environment(self) -> Callable[ - [gcdc_environment.UpdateEnvironmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_environment(self) -> Callable[ - [environment.DeleteEnvironmentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def lookup_environment_history(self) -> Callable[ - [environment.LookupEnvironmentHistoryRequest], - Union[ - environment.LookupEnvironmentHistoryResponse, - Awaitable[environment.LookupEnvironmentHistoryResponse] - ]]: - raise NotImplementedError() - - @property - def run_continuous_test(self) -> Callable[ - [environment.RunContinuousTestRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_continuous_test_results(self) -> Callable[ - [environment.ListContinuousTestResultsRequest], - Union[ - environment.ListContinuousTestResultsResponse, - Awaitable[environment.ListContinuousTestResultsResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'EnvironmentsTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py deleted file mode 100644 index 59d45c65..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py +++ /dev/null @@ -1,461 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import environment -from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment -from google.longrunning import operations_pb2 # type: ignore -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.cx.v3beta1.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] = {} - 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_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - environment.ListEnvironmentsResponse]: - r"""Return a callable for the list environments method over gRPC. - - Returns the list of all environments in the specified - [Agent][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.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 - [Environment][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Environments/GetEnvironment', - request_serializer=environment.GetEnvironmentRequest.serialize, - response_deserializer=environment.Environment.deserialize, - ) - return self._stubs['get_environment'] - - @property - def create_environment(self) -> Callable[ - [gcdc_environment.CreateEnvironmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the create environment method over gRPC. - - Creates an - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in - the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. - - Returns: - Callable[[~.CreateEnvironmentRequest], - ~.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_environment' not in self._stubs: - self._stubs['create_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Environments/CreateEnvironment', - request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_environment'] - - @property - def update_environment(self) -> Callable[ - [gcdc_environment.UpdateEnvironmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the update environment method over gRPC. - - Updates the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Returns: - Callable[[~.UpdateEnvironmentRequest], - ~.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_environment' not in self._stubs: - self._stubs['update_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Environments/UpdateEnvironment', - request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - 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 - [Environment][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Environments/DeleteEnvironment', - request_serializer=environment.DeleteEnvironmentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_environment'] - - @property - def lookup_environment_history(self) -> Callable[ - [environment.LookupEnvironmentHistoryRequest], - environment.LookupEnvironmentHistoryResponse]: - r"""Return a callable for the lookup environment history method over gRPC. - - Looks up the history of the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Returns: - Callable[[~.LookupEnvironmentHistoryRequest], - ~.LookupEnvironmentHistoryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'lookup_environment_history' not in self._stubs: - self._stubs['lookup_environment_history'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Environments/LookupEnvironmentHistory', - request_serializer=environment.LookupEnvironmentHistoryRequest.serialize, - response_deserializer=environment.LookupEnvironmentHistoryResponse.deserialize, - ) - return self._stubs['lookup_environment_history'] - - @property - def run_continuous_test(self) -> Callable[ - [environment.RunContinuousTestRequest], - operations_pb2.Operation]: - r"""Return a callable for the run continuous test method over gRPC. - - Kicks off a continuous test under the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Returns: - Callable[[~.RunContinuousTestRequest], - ~.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 'run_continuous_test' not in self._stubs: - self._stubs['run_continuous_test'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Environments/RunContinuousTest', - request_serializer=environment.RunContinuousTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_continuous_test'] - - @property - def list_continuous_test_results(self) -> Callable[ - [environment.ListContinuousTestResultsRequest], - environment.ListContinuousTestResultsResponse]: - r"""Return a callable for the list continuous test results method over gRPC. - - Fetches a list of continuous test results for a given - environment. - - Returns: - Callable[[~.ListContinuousTestResultsRequest], - ~.ListContinuousTestResultsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_continuous_test_results' not in self._stubs: - self._stubs['list_continuous_test_results'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Environments/ListContinuousTestResults', - request_serializer=environment.ListContinuousTestResultsRequest.serialize, - response_deserializer=environment.ListContinuousTestResultsResponse.deserialize, - ) - return self._stubs['list_continuous_test_results'] - - -__all__ = ( - 'EnvironmentsGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py deleted file mode 100644 index 8bdca952..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py +++ /dev/null @@ -1,465 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import environment -from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .grpc import EnvironmentsGrpcTransport - - -class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): - """gRPC AsyncIO backend transport for Environments. - - Service for managing - [Environments][google.cloud.dialogflow.cx.v3beta1.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] = {} - 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_environments(self) -> Callable[ - [environment.ListEnvironmentsRequest], - Awaitable[environment.ListEnvironmentsResponse]]: - r"""Return a callable for the list environments method over gRPC. - - Returns the list of all environments in the specified - [Agent][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.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 - [Environment][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Environments/GetEnvironment', - request_serializer=environment.GetEnvironmentRequest.serialize, - response_deserializer=environment.Environment.deserialize, - ) - return self._stubs['get_environment'] - - @property - def create_environment(self) -> Callable[ - [gcdc_environment.CreateEnvironmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create environment method over gRPC. - - Creates an - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] in - the specified [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. - - Returns: - Callable[[~.CreateEnvironmentRequest], - 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_environment' not in self._stubs: - self._stubs['create_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Environments/CreateEnvironment', - request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_environment'] - - @property - def update_environment(self) -> Callable[ - [gcdc_environment.UpdateEnvironmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update environment method over gRPC. - - Updates the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Returns: - Callable[[~.UpdateEnvironmentRequest], - 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_environment' not in self._stubs: - self._stubs['update_environment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Environments/UpdateEnvironment', - request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - 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 - [Environment][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Environments/DeleteEnvironment', - request_serializer=environment.DeleteEnvironmentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_environment'] - - @property - def lookup_environment_history(self) -> Callable[ - [environment.LookupEnvironmentHistoryRequest], - Awaitable[environment.LookupEnvironmentHistoryResponse]]: - r"""Return a callable for the lookup environment history method over gRPC. - - Looks up the history of the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Returns: - Callable[[~.LookupEnvironmentHistoryRequest], - Awaitable[~.LookupEnvironmentHistoryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'lookup_environment_history' not in self._stubs: - self._stubs['lookup_environment_history'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Environments/LookupEnvironmentHistory', - request_serializer=environment.LookupEnvironmentHistoryRequest.serialize, - response_deserializer=environment.LookupEnvironmentHistoryResponse.deserialize, - ) - return self._stubs['lookup_environment_history'] - - @property - def run_continuous_test(self) -> Callable[ - [environment.RunContinuousTestRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run continuous test method over gRPC. - - Kicks off a continuous test under the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Returns: - Callable[[~.RunContinuousTestRequest], - 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 'run_continuous_test' not in self._stubs: - self._stubs['run_continuous_test'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Environments/RunContinuousTest', - request_serializer=environment.RunContinuousTestRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_continuous_test'] - - @property - def list_continuous_test_results(self) -> Callable[ - [environment.ListContinuousTestResultsRequest], - Awaitable[environment.ListContinuousTestResultsResponse]]: - r"""Return a callable for the list continuous test results method over gRPC. - - Fetches a list of continuous test results for a given - environment. - - Returns: - Callable[[~.ListContinuousTestResultsRequest], - Awaitable[~.ListContinuousTestResultsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_continuous_test_results' not in self._stubs: - self._stubs['list_continuous_test_results'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Environments/ListContinuousTestResults', - request_serializer=environment.ListContinuousTestResultsRequest.serialize, - response_deserializer=environment.ListContinuousTestResultsResponse.deserialize, - ) - return self._stubs['list_continuous_test_results'] - - -__all__ = ( - 'EnvironmentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py deleted file mode 100644 index 6d4dd817..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/__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 ExperimentsClient -from .async_client import ExperimentsAsyncClient - -__all__ = ( - 'ExperimentsClient', - 'ExperimentsAsyncClient', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py deleted file mode 100644 index 1c87294c..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py +++ /dev/null @@ -1,740 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.experiments import pagers -from google.cloud.dialogflowcx_v3beta1.types import experiment -from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport -from .client import ExperimentsClient - - -class ExperimentsAsyncClient: - """Service for managing - [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. - """ - - _client: ExperimentsClient - - DEFAULT_ENDPOINT = ExperimentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ExperimentsClient.DEFAULT_MTLS_ENDPOINT - - experiment_path = staticmethod(ExperimentsClient.experiment_path) - parse_experiment_path = staticmethod(ExperimentsClient.parse_experiment_path) - version_path = staticmethod(ExperimentsClient.version_path) - parse_version_path = staticmethod(ExperimentsClient.parse_version_path) - common_billing_account_path = staticmethod(ExperimentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ExperimentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ExperimentsClient.common_folder_path) - parse_common_folder_path = staticmethod(ExperimentsClient.parse_common_folder_path) - common_organization_path = staticmethod(ExperimentsClient.common_organization_path) - parse_common_organization_path = staticmethod(ExperimentsClient.parse_common_organization_path) - common_project_path = staticmethod(ExperimentsClient.common_project_path) - parse_common_project_path = staticmethod(ExperimentsClient.parse_common_project_path) - common_location_path = staticmethod(ExperimentsClient.common_location_path) - parse_common_location_path = staticmethod(ExperimentsClient.parse_common_location_path) - - @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: - ExperimentsAsyncClient: The constructed client. - """ - return ExperimentsClient.from_service_account_info.__func__(ExperimentsAsyncClient, 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: - ExperimentsAsyncClient: The constructed client. - """ - return ExperimentsClient.from_service_account_file.__func__(ExperimentsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> ExperimentsTransport: - """Returns the transport used by the client instance. - - Returns: - ExperimentsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ExperimentsClient).get_transport_class, type(ExperimentsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, ExperimentsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the experiments 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, ~.ExperimentsTransport]): 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 = ExperimentsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_experiments(self, - request: experiment.ListExperimentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExperimentsAsyncPager: - r"""Returns the list of all experiments in the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsRequest`): - The request object. The request message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. - parent (:class:`str`): - Required. The - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - to list all environments for. Format: - ``projects//locations//agents//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.experiments.pagers.ListExperimentsAsyncPager: - The response message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. - - 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 = experiment.ListExperimentsRequest(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_experiments, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListExperimentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_experiment(self, - request: experiment.GetExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Retrieves the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetExperimentRequest`): - The request object. The request message for - [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.GetExperiment]. - name (:class:`str`): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = experiment.GetExperimentRequest(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_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_experiment(self, - request: gcdc_experiment.CreateExperimentRequest = None, - *, - parent: str = None, - experiment: gcdc_experiment.Experiment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_experiment.Experiment: - r"""Creates an - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in - the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateExperimentRequest`): - The request object. The request message for - [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.CreateExperiment]. - parent (:class:`str`): - Required. The - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to - create an - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - for. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - experiment (:class:`google.cloud.dialogflowcx_v3beta1.types.Experiment`): - Required. The experiment to create. - This corresponds to the ``experiment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, experiment]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_experiment.CreateExperimentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if experiment is not None: - request.experiment = experiment - - # 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_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_experiment(self, - request: gcdc_experiment.UpdateExperimentRequest = None, - *, - experiment: gcdc_experiment.Experiment = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_experiment.Experiment: - r"""Updates the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateExperimentRequest`): - The request object. The request message for - [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.UpdateExperiment]. - experiment (:class:`google.cloud.dialogflowcx_v3beta1.types.Experiment`): - Required. The experiment to update. - This corresponds to the ``experiment`` 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.dialogflowcx_v3beta1.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([experiment, 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 = gcdc_experiment.UpdateExperimentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if experiment is not None: - request.experiment = experiment - if update_mask is not None: - 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_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("experiment.name", request.experiment.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_experiment(self, - request: experiment.DeleteExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteExperimentRequest`): - The request object. The request message for - [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.DeleteExperiment]. - name (:class:`str`): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - to delete. Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = experiment.DeleteExperimentRequest(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_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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 start_experiment(self, - request: experiment.StartExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Starts the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - This rpc only changes the state of experiment from PENDING to - RUNNING. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.StartExperimentRequest`): - The request object. The request message for - [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StartExperiment]. - name (:class:`str`): - Required. Resource name of the experiment to start. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = experiment.StartExperimentRequest(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.start_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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 stop_experiment(self, - request: experiment.StopExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Stops the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - This rpc only changes the state of experiment from RUNNING to - DONE. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.StopExperimentRequest`): - The request object. The request message for - [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StopExperiment]. - name (:class:`str`): - Required. Resource name of the experiment to stop. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = experiment.StopExperimentRequest(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.stop_experiment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ExperimentsAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py deleted file mode 100644 index fde48084..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py +++ /dev/null @@ -1,936 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.experiments import pagers -from google.cloud.dialogflowcx_v3beta1.types import experiment -from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ExperimentsGrpcTransport -from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport - - -class ExperimentsClientMeta(type): - """Metaclass for the Experiments 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[ExperimentsTransport]] - _transport_registry["grpc"] = ExperimentsGrpcTransport - _transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[ExperimentsTransport]: - """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 ExperimentsClient(metaclass=ExperimentsClientMeta): - """Service for managing - [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. - """ - - @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: - ExperimentsClient: 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: - ExperimentsClient: 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) -> ExperimentsTransport: - """Returns the transport used by the client instance. - - Returns: - ExperimentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def experiment_path(project: str,location: str,agent: str,environment: str,experiment: str,) -> str: - """Returns a fully-qualified experiment string.""" - return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format(project=project, location=location, agent=agent, environment=environment, experiment=experiment, ) - - @staticmethod - def parse_experiment_path(path: str) -> Dict[str,str]: - """Parses a experiment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/experiments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def version_path(project: str,location: str,agent: str,flow: str,version: str,) -> str: - """Returns a fully-qualified version string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - - @staticmethod - def parse_version_path(path: str) -> Dict[str,str]: - """Parses a version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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, ExperimentsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the experiments 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, ExperimentsTransport]): 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, ExperimentsTransport): - # transport is a ExperimentsTransport 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_experiments(self, - request: experiment.ListExperimentsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExperimentsPager: - r"""Returns the list of all experiments in the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsRequest): - The request object. The request message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. - parent (str): - Required. The - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - to list all environments for. Format: - ``projects//locations//agents//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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.experiments.pagers.ListExperimentsPager: - The response message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. - - 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 experiment.ListExperimentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, experiment.ListExperimentsRequest): - request = experiment.ListExperimentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_experiments] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListExperimentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_experiment(self, - request: experiment.GetExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Retrieves the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetExperimentRequest): - The request object. The request message for - [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.GetExperiment]. - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a experiment.GetExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, experiment.GetExperimentRequest): - request = experiment.GetExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_experiment] - - # Certain fields should be provided 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_experiment(self, - request: gcdc_experiment.CreateExperimentRequest = None, - *, - parent: str = None, - experiment: gcdc_experiment.Experiment = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_experiment.Experiment: - r"""Creates an - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in - the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateExperimentRequest): - The request object. The request message for - [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.CreateExperiment]. - parent (str): - Required. The - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to - create an - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - for. Format: - ``projects//locations//agents//environments/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - experiment (google.cloud.dialogflowcx_v3beta1.types.Experiment): - Required. The experiment to create. - This corresponds to the ``experiment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, experiment]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_experiment.CreateExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_experiment.CreateExperimentRequest): - request = gcdc_experiment.CreateExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if experiment is not None: - request.experiment = experiment - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_experiment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_experiment(self, - request: gcdc_experiment.UpdateExperimentRequest = None, - *, - experiment: gcdc_experiment.Experiment = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_experiment.Experiment: - r"""Updates the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateExperimentRequest): - The request object. The request message for - [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.UpdateExperiment]. - experiment (google.cloud.dialogflowcx_v3beta1.types.Experiment): - Required. The experiment to update. - This corresponds to the ``experiment`` 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.dialogflowcx_v3beta1.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([experiment, 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 gcdc_experiment.UpdateExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_experiment.UpdateExperimentRequest): - request = gcdc_experiment.UpdateExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if experiment is not None: - request.experiment = experiment - if update_mask is not None: - 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_experiment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("experiment.name", request.experiment.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_experiment(self, - request: experiment.DeleteExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.DeleteExperimentRequest): - The request object. The request message for - [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.DeleteExperiment]. - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - to delete. Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 experiment.DeleteExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, experiment.DeleteExperimentRequest): - request = experiment.DeleteExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_experiment] - - # Certain fields should be 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 start_experiment(self, - request: experiment.StartExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Starts the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - This rpc only changes the state of experiment from PENDING to - RUNNING. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.StartExperimentRequest): - The request object. The request message for - [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StartExperiment]. - name (str): - Required. Resource name of the experiment to start. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a experiment.StartExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, experiment.StartExperimentRequest): - request = experiment.StartExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.start_experiment] - - # Certain fields should be provided 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 stop_experiment(self, - request: experiment.StopExperimentRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> experiment.Experiment: - r"""Stops the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - This rpc only changes the state of experiment from RUNNING to - DONE. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.StopExperimentRequest): - The request object. The request message for - [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StopExperiment]. - name (str): - Required. Resource name of the experiment to stop. - Format: - ``projects//locations//agents//environments//experiments/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Experiment: - Represents an experiment in an - environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a experiment.StopExperimentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, experiment.StopExperimentRequest): - request = experiment.StopExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.stop_experiment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "ExperimentsClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py deleted file mode 100644 index 8d269bae..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/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.dialogflowcx_v3beta1.types import experiment - - -class ListExperimentsPager: - """A pager for iterating through ``list_experiments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``experiments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListExperiments`` requests and continue to iterate - through the ``experiments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse` - 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[..., experiment.ListExperimentsResponse], - request: experiment.ListExperimentsRequest, - response: experiment.ListExperimentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse): - 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 = experiment.ListExperimentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[experiment.ListExperimentsResponse]: - 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[experiment.Experiment]: - for page in self.pages: - yield from page.experiments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListExperimentsAsyncPager: - """A pager for iterating through ``list_experiments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``experiments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListExperiments`` requests and continue to iterate - through the ``experiments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse` - 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[experiment.ListExperimentsResponse]], - request: experiment.ListExperimentsRequest, - response: experiment.ListExperimentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListExperimentsResponse): - 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 = experiment.ListExperimentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[experiment.ListExperimentsResponse]: - 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[experiment.Experiment]: - async def async_generator(): - async for page in self.pages: - for response in page.experiments: - 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py deleted file mode 100644 index 80f4c26e..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/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 ExperimentsTransport -from .grpc import ExperimentsGrpcTransport -from .grpc_asyncio import ExperimentsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ExperimentsTransport]] -_transport_registry['grpc'] = ExperimentsGrpcTransport -_transport_registry['grpc_asyncio'] = ExperimentsGrpcAsyncIOTransport - -__all__ = ( - 'ExperimentsTransport', - 'ExperimentsGrpcTransport', - 'ExperimentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py deleted file mode 100644 index 21e09b9d..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import experiment -from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -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-dialogflowcx', - ).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 ExperimentsTransport(abc.ABC): - """Abstract transport class for Experiments.""" - - 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_experiments: gapic_v1.method.wrap_method( - self.list_experiments, - default_timeout=None, - client_info=client_info, - ), - self.get_experiment: gapic_v1.method.wrap_method( - self.get_experiment, - default_timeout=None, - client_info=client_info, - ), - self.create_experiment: gapic_v1.method.wrap_method( - self.create_experiment, - default_timeout=None, - client_info=client_info, - ), - self.update_experiment: gapic_v1.method.wrap_method( - self.update_experiment, - default_timeout=None, - client_info=client_info, - ), - self.delete_experiment: gapic_v1.method.wrap_method( - self.delete_experiment, - default_timeout=None, - client_info=client_info, - ), - self.start_experiment: gapic_v1.method.wrap_method( - self.start_experiment, - default_timeout=None, - client_info=client_info, - ), - self.stop_experiment: gapic_v1.method.wrap_method( - self.stop_experiment, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_experiments(self) -> Callable[ - [experiment.ListExperimentsRequest], - Union[ - experiment.ListExperimentsResponse, - Awaitable[experiment.ListExperimentsResponse] - ]]: - raise NotImplementedError() - - @property - def get_experiment(self) -> Callable[ - [experiment.GetExperimentRequest], - Union[ - experiment.Experiment, - Awaitable[experiment.Experiment] - ]]: - raise NotImplementedError() - - @property - def create_experiment(self) -> Callable[ - [gcdc_experiment.CreateExperimentRequest], - Union[ - gcdc_experiment.Experiment, - Awaitable[gcdc_experiment.Experiment] - ]]: - raise NotImplementedError() - - @property - def update_experiment(self) -> Callable[ - [gcdc_experiment.UpdateExperimentRequest], - Union[ - gcdc_experiment.Experiment, - Awaitable[gcdc_experiment.Experiment] - ]]: - raise NotImplementedError() - - @property - def delete_experiment(self) -> Callable[ - [experiment.DeleteExperimentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def start_experiment(self) -> Callable[ - [experiment.StartExperimentRequest], - Union[ - experiment.Experiment, - Awaitable[experiment.Experiment] - ]]: - raise NotImplementedError() - - @property - def stop_experiment(self) -> Callable[ - [experiment.StopExperimentRequest], - Union[ - experiment.Experiment, - Awaitable[experiment.Experiment] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'ExperimentsTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py deleted file mode 100644 index 0e4f5139..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.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. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflowcx_v3beta1.types import experiment -from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -from google.protobuf import empty_pb2 # type: ignore -from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO - - -class ExperimentsGrpcTransport(ExperimentsTransport): - """gRPC backend transport for Experiments. - - Service for managing - [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - 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_experiments(self) -> Callable[ - [experiment.ListExperimentsRequest], - experiment.ListExperimentsResponse]: - r"""Return a callable for the list experiments method over gRPC. - - Returns the list of all experiments in the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Returns: - Callable[[~.ListExperimentsRequest], - ~.ListExperimentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_experiments' not in self._stubs: - self._stubs['list_experiments'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/ListExperiments', - request_serializer=experiment.ListExperimentsRequest.serialize, - response_deserializer=experiment.ListExperimentsResponse.deserialize, - ) - return self._stubs['list_experiments'] - - @property - def get_experiment(self) -> Callable[ - [experiment.GetExperimentRequest], - experiment.Experiment]: - r"""Return a callable for the get experiment method over gRPC. - - Retrieves the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Returns: - Callable[[~.GetExperimentRequest], - ~.Experiment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_experiment' not in self._stubs: - self._stubs['get_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/GetExperiment', - request_serializer=experiment.GetExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['get_experiment'] - - @property - def create_experiment(self) -> Callable[ - [gcdc_experiment.CreateExperimentRequest], - gcdc_experiment.Experiment]: - r"""Return a callable for the create experiment method over gRPC. - - Creates an - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in - the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Returns: - Callable[[~.CreateExperimentRequest], - ~.Experiment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_experiment' not in self._stubs: - self._stubs['create_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/CreateExperiment', - request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, - response_deserializer=gcdc_experiment.Experiment.deserialize, - ) - return self._stubs['create_experiment'] - - @property - def update_experiment(self) -> Callable[ - [gcdc_experiment.UpdateExperimentRequest], - gcdc_experiment.Experiment]: - r"""Return a callable for the update experiment method over gRPC. - - Updates the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Returns: - Callable[[~.UpdateExperimentRequest], - ~.Experiment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_experiment' not in self._stubs: - self._stubs['update_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/UpdateExperiment', - request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, - response_deserializer=gcdc_experiment.Experiment.deserialize, - ) - return self._stubs['update_experiment'] - - @property - def delete_experiment(self) -> Callable[ - [experiment.DeleteExperimentRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete experiment method over gRPC. - - Deletes the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Returns: - Callable[[~.DeleteExperimentRequest], - ~.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_experiment' not in self._stubs: - self._stubs['delete_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/DeleteExperiment', - request_serializer=experiment.DeleteExperimentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_experiment'] - - @property - def start_experiment(self) -> Callable[ - [experiment.StartExperimentRequest], - experiment.Experiment]: - r"""Return a callable for the start experiment method over gRPC. - - Starts the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - This rpc only changes the state of experiment from PENDING to - RUNNING. - - Returns: - Callable[[~.StartExperimentRequest], - ~.Experiment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_experiment' not in self._stubs: - self._stubs['start_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/StartExperiment', - request_serializer=experiment.StartExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['start_experiment'] - - @property - def stop_experiment(self) -> Callable[ - [experiment.StopExperimentRequest], - experiment.Experiment]: - r"""Return a callable for the stop experiment method over gRPC. - - Stops the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - This rpc only changes the state of experiment from RUNNING to - DONE. - - Returns: - Callable[[~.StopExperimentRequest], - ~.Experiment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_experiment' not in self._stubs: - self._stubs['stop_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/StopExperiment', - request_serializer=experiment.StopExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['stop_experiment'] - - -__all__ = ( - 'ExperimentsGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py deleted file mode 100644 index ee9dfee7..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py +++ /dev/null @@ -1,424 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import experiment -from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -from google.protobuf import empty_pb2 # type: ignore -from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO -from .grpc import ExperimentsGrpcTransport - - -class ExperimentsGrpcAsyncIOTransport(ExperimentsTransport): - """gRPC AsyncIO backend transport for Experiments. - - Service for managing - [Experiments][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - 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_experiments(self) -> Callable[ - [experiment.ListExperimentsRequest], - Awaitable[experiment.ListExperimentsResponse]]: - r"""Return a callable for the list experiments method over gRPC. - - Returns the list of all experiments in the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Returns: - Callable[[~.ListExperimentsRequest], - Awaitable[~.ListExperimentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_experiments' not in self._stubs: - self._stubs['list_experiments'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/ListExperiments', - request_serializer=experiment.ListExperimentsRequest.serialize, - response_deserializer=experiment.ListExperimentsResponse.deserialize, - ) - return self._stubs['list_experiments'] - - @property - def get_experiment(self) -> Callable[ - [experiment.GetExperimentRequest], - Awaitable[experiment.Experiment]]: - r"""Return a callable for the get experiment method over gRPC. - - Retrieves the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Returns: - Callable[[~.GetExperimentRequest], - Awaitable[~.Experiment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_experiment' not in self._stubs: - self._stubs['get_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/GetExperiment', - request_serializer=experiment.GetExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['get_experiment'] - - @property - def create_experiment(self) -> Callable[ - [gcdc_experiment.CreateExperimentRequest], - Awaitable[gcdc_experiment.Experiment]]: - r"""Return a callable for the create experiment method over gRPC. - - Creates an - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment] in - the specified - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - - Returns: - Callable[[~.CreateExperimentRequest], - Awaitable[~.Experiment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_experiment' not in self._stubs: - self._stubs['create_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/CreateExperiment', - request_serializer=gcdc_experiment.CreateExperimentRequest.serialize, - response_deserializer=gcdc_experiment.Experiment.deserialize, - ) - return self._stubs['create_experiment'] - - @property - def update_experiment(self) -> Callable[ - [gcdc_experiment.UpdateExperimentRequest], - Awaitable[gcdc_experiment.Experiment]]: - r"""Return a callable for the update experiment method over gRPC. - - Updates the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Returns: - Callable[[~.UpdateExperimentRequest], - Awaitable[~.Experiment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_experiment' not in self._stubs: - self._stubs['update_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/UpdateExperiment', - request_serializer=gcdc_experiment.UpdateExperimentRequest.serialize, - response_deserializer=gcdc_experiment.Experiment.deserialize, - ) - return self._stubs['update_experiment'] - - @property - def delete_experiment(self) -> Callable[ - [experiment.DeleteExperimentRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete experiment method over gRPC. - - Deletes the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - - Returns: - Callable[[~.DeleteExperimentRequest], - 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_experiment' not in self._stubs: - self._stubs['delete_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/DeleteExperiment', - request_serializer=experiment.DeleteExperimentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_experiment'] - - @property - def start_experiment(self) -> Callable[ - [experiment.StartExperimentRequest], - Awaitable[experiment.Experiment]]: - r"""Return a callable for the start experiment method over gRPC. - - Starts the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - This rpc only changes the state of experiment from PENDING to - RUNNING. - - Returns: - Callable[[~.StartExperimentRequest], - Awaitable[~.Experiment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'start_experiment' not in self._stubs: - self._stubs['start_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/StartExperiment', - request_serializer=experiment.StartExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['start_experiment'] - - @property - def stop_experiment(self) -> Callable[ - [experiment.StopExperimentRequest], - Awaitable[experiment.Experiment]]: - r"""Return a callable for the stop experiment method over gRPC. - - Stops the specified - [Experiment][google.cloud.dialogflow.cx.v3beta1.Experiment]. - This rpc only changes the state of experiment from RUNNING to - DONE. - - Returns: - Callable[[~.StopExperimentRequest], - Awaitable[~.Experiment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_experiment' not in self._stubs: - self._stubs['stop_experiment'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Experiments/StopExperiment', - request_serializer=experiment.StopExperimentRequest.serialize, - response_deserializer=experiment.Experiment.deserialize, - ) - return self._stubs['stop_experiment'] - - -__all__ = ( - 'ExperimentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py deleted file mode 100644 index 42e3f705..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/__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 FlowsClient -from .async_client import FlowsAsyncClient - -__all__ = ( - 'FlowsClient', - 'FlowsAsyncClient', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py deleted file mode 100644 index 0c60a6f7..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py +++ /dev/null @@ -1,1010 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.flows import pagers -from google.cloud.dialogflowcx_v3beta1.types import flow -from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import validation_message -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport -from .client import FlowsClient - - -class FlowsAsyncClient: - """Service for managing - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow]. - """ - - _client: FlowsClient - - DEFAULT_ENDPOINT = FlowsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = FlowsClient.DEFAULT_MTLS_ENDPOINT - - flow_path = staticmethod(FlowsClient.flow_path) - parse_flow_path = staticmethod(FlowsClient.parse_flow_path) - flow_validation_result_path = staticmethod(FlowsClient.flow_validation_result_path) - parse_flow_validation_result_path = staticmethod(FlowsClient.parse_flow_validation_result_path) - intent_path = staticmethod(FlowsClient.intent_path) - parse_intent_path = staticmethod(FlowsClient.parse_intent_path) - page_path = staticmethod(FlowsClient.page_path) - parse_page_path = staticmethod(FlowsClient.parse_page_path) - transition_route_group_path = staticmethod(FlowsClient.transition_route_group_path) - parse_transition_route_group_path = staticmethod(FlowsClient.parse_transition_route_group_path) - webhook_path = staticmethod(FlowsClient.webhook_path) - parse_webhook_path = staticmethod(FlowsClient.parse_webhook_path) - common_billing_account_path = staticmethod(FlowsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(FlowsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(FlowsClient.common_folder_path) - parse_common_folder_path = staticmethod(FlowsClient.parse_common_folder_path) - common_organization_path = staticmethod(FlowsClient.common_organization_path) - parse_common_organization_path = staticmethod(FlowsClient.parse_common_organization_path) - common_project_path = staticmethod(FlowsClient.common_project_path) - parse_common_project_path = staticmethod(FlowsClient.parse_common_project_path) - common_location_path = staticmethod(FlowsClient.common_location_path) - parse_common_location_path = staticmethod(FlowsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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: - FlowsAsyncClient: The constructed client. - """ - return FlowsClient.from_service_account_info.__func__(FlowsAsyncClient, 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: - FlowsAsyncClient: The constructed client. - """ - return FlowsClient.from_service_account_file.__func__(FlowsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> FlowsTransport: - """Returns the transport used by the client instance. - - Returns: - FlowsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(FlowsClient).get_transport_class, type(FlowsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, FlowsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the flows 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, ~.FlowsTransport]): 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 = FlowsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_flow(self, - request: gcdc_flow.CreateFlowRequest = None, - *, - parent: str = None, - flow: gcdc_flow.Flow = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_flow.Flow: - r"""Creates a flow in the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateFlowRequest`): - The request object. The request message for - [Flows.CreateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.CreateFlow]. - parent (:class:`str`): - Required. The agent to create a flow for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - flow (:class:`google.cloud.dialogflowcx_v3beta1.types.Flow`): - Required. The flow to create. - This corresponds to the ``flow`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, flow]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_flow.CreateFlowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if flow is not None: - request.flow = flow - - # 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_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_flow(self, - request: flow.DeleteFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteFlowRequest`): - The request object. The request message for - [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3beta1.Flows.DeleteFlow]. - name (:class:`str`): - Required. The name of the flow to delete. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = flow.DeleteFlowRequest(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_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_flows(self, - request: flow.ListFlowsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFlowsAsyncPager: - r"""Returns the list of all flows in the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsRequest`): - The request object. The request message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. - parent (:class:`str`): - Required. The agent containing the flows. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.flows.pagers.ListFlowsAsyncPager: - The response message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. - - 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 = flow.ListFlowsRequest(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_flows, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListFlowsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_flow(self, - request: flow.GetFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.Flow: - r"""Retrieves the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetFlowRequest`): - The request object. The response message for - [Flows.GetFlow][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlow]. - name (:class:`str`): - Required. The name of the flow to get. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = flow.GetFlowRequest(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_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_flow(self, - request: gcdc_flow.UpdateFlowRequest = None, - *, - flow: gcdc_flow.Flow = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_flow.Flow: - r"""Updates the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateFlowRequest`): - The request object. The request message for - [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.UpdateFlow]. - flow (:class:`google.cloud.dialogflowcx_v3beta1.types.Flow`): - Required. The flow to update. - This corresponds to the ``flow`` 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 ``update_mask`` is not specified, an error will be - returned. - - 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.dialogflowcx_v3beta1.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([flow, 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 = gcdc_flow.UpdateFlowRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if flow is not None: - request.flow = flow - if update_mask is not None: - 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_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("flow.name", request.flow.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def train_flow(self, - request: flow.TrainFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Trains the specified flow. Note that only the flow in - 'draft' environment is trained. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.TrainFlowRequest`): - The request object. The request message for - [Flows.TrainFlow][google.cloud.dialogflow.cx.v3beta1.Flows.TrainFlow]. - name (:class:`str`): - Required. The flow to train. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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 = flow.TrainFlowRequest(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.train_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def validate_flow(self, - request: flow.ValidateFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.FlowValidationResult: - r"""Validates the specified flow and creates or updates - validation results. Please call this API after the - training is completed to get the complete validation - results. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ValidateFlowRequest`): - The request object. The request message for - [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ValidateFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.FlowValidationResult: - The response message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. - - """ - # Create or coerce a protobuf request object. - request = flow.ValidateFlowRequest(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.validate_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_flow_validation_result(self, - request: flow.GetFlowValidationResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.FlowValidationResult: - r"""Gets the latest flow validation result. Flow - validation is performed when ValidateFlow is called. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetFlowValidationResultRequest`): - The request object. The request message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. - name (:class:`str`): - Required. The flow name. Format: - ``projects//locations//agents//flows//validationResult``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.FlowValidationResult: - The response message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = flow.GetFlowValidationResultRequest(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_flow_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(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_flow(self, - request: flow.ImportFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Imports the specified flow to the specified agent - from a binary file. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest`): - The request object. The request message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.ImportFlowResponse` - The response message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. - - """ - # Create or coerce a protobuf request object. - request = flow.ImportFlowRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - flow.ImportFlowResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - async def export_flow(self, - request: flow.ExportFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowRequest`): - The request object. The request message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowResponse` - The response message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. - - """ - # Create or coerce a protobuf request object. - request = flow.ExportFlowRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_flow, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - flow.ExportFlowResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "FlowsAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/client.py deleted file mode 100644 index 16366dcd..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/client.py +++ /dev/null @@ -1,1245 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.flows import pagers -from google.cloud.dialogflowcx_v3beta1.types import flow -from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import validation_message -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import FlowsGrpcTransport -from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport - - -class FlowsClientMeta(type): - """Metaclass for the Flows 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[FlowsTransport]] - _transport_registry["grpc"] = FlowsGrpcTransport - _transport_registry["grpc_asyncio"] = FlowsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[FlowsTransport]: - """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 FlowsClient(metaclass=FlowsClientMeta): - """Service for managing - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow]. - """ - - @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: - FlowsClient: 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: - FlowsClient: 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) -> FlowsTransport: - """Returns the transport used by the client instance. - - Returns: - FlowsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_validation_result_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow_validation_result string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_validation_result_path(path: str) -> Dict[str,str]: - """Parses a flow_validation_result path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: - """Returns a fully-qualified page string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - - @staticmethod - def parse_page_path(path: str) -> Dict[str,str]: - """Parses a page path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: - """Returns a fully-qualified transition_route_group string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - - @staticmethod - def parse_transition_route_group_path(path: str) -> Dict[str,str]: - """Parses a transition_route_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, FlowsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the flows 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, FlowsTransport]): 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, FlowsTransport): - # transport is a FlowsTransport 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_flow(self, - request: gcdc_flow.CreateFlowRequest = None, - *, - parent: str = None, - flow: gcdc_flow.Flow = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_flow.Flow: - r"""Creates a flow in the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateFlowRequest): - The request object. The request message for - [Flows.CreateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.CreateFlow]. - parent (str): - Required. The agent to create a flow for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - flow (google.cloud.dialogflowcx_v3beta1.types.Flow): - Required. The flow to create. - This corresponds to the ``flow`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, flow]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_flow.CreateFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_flow.CreateFlowRequest): - request = gcdc_flow.CreateFlowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if flow is not None: - request.flow = flow - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_flow(self, - request: flow.DeleteFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a specified flow. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.DeleteFlowRequest): - The request object. The request message for - [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3beta1.Flows.DeleteFlow]. - name (str): - Required. The name of the flow to delete. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 flow.DeleteFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.DeleteFlowRequest): - request = flow.DeleteFlowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_flows(self, - request: flow.ListFlowsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFlowsPager: - r"""Returns the list of all flows in the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListFlowsRequest): - The request object. The request message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. - parent (str): - Required. The agent containing the flows. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.flows.pagers.ListFlowsPager: - The response message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. - - 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 flow.ListFlowsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.ListFlowsRequest): - request = flow.ListFlowsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_flows] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListFlowsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_flow(self, - request: flow.GetFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.Flow: - r"""Retrieves the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetFlowRequest): - The request object. The response message for - [Flows.GetFlow][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlow]. - name (str): - Required. The name of the flow to get. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 flow.GetFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.GetFlowRequest): - request = flow.GetFlowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_flow(self, - request: gcdc_flow.UpdateFlowRequest = None, - *, - flow: gcdc_flow.Flow = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_flow.Flow: - r"""Updates the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateFlowRequest): - The request object. The request message for - [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.UpdateFlow]. - flow (google.cloud.dialogflowcx_v3beta1.types.Flow): - Required. The flow to update. - This corresponds to the ``flow`` 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 ``update_mask`` is not specified, an error will be - returned. - - 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.dialogflowcx_v3beta1.types.Flow: - Flows represents the conversation - flows when you build your chatbot agent. - A flow consists of many pages connected - by the transition routes. Conversations - always start with the built-in Start - Flow (with an all-0 ID). Transition - routes can direct the conversation - session from the current flow (parent - flow) to another flow (sub flow). When - the sub flow is finished, Dialogflow - will bring the session back to the - parent flow, where the sub flow is - started. - - Usually, when a transition route is - followed by a matched intent, the intent - will be "consumed". This means the - intent won't activate more transition - routes. However, when the followed - transition route moves the conversation - session into a different flow, the - matched intent can be carried over and - to be consumed in the target flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([flow, 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 gcdc_flow.UpdateFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_flow.UpdateFlowRequest): - request = gcdc_flow.UpdateFlowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if flow is not None: - request.flow = flow - if update_mask is not None: - 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_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("flow.name", request.flow.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def train_flow(self, - request: flow.TrainFlowRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Trains the specified flow. Note that only the flow in - 'draft' environment is trained. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.TrainFlowRequest): - The request object. The request message for - [Flows.TrainFlow][google.cloud.dialogflow.cx.v3beta1.Flows.TrainFlow]. - name (str): - Required. The flow to train. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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 flow.TrainFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.TrainFlowRequest): - request = flow.TrainFlowRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.train_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def validate_flow(self, - request: flow.ValidateFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.FlowValidationResult: - r"""Validates the specified flow and creates or updates - validation results. Please call this API after the - training is completed to get the complete validation - results. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ValidateFlowRequest): - The request object. The request message for - [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ValidateFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.FlowValidationResult: - The response message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a flow.ValidateFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.ValidateFlowRequest): - request = flow.ValidateFlowRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.validate_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_flow_validation_result(self, - request: flow.GetFlowValidationResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> flow.FlowValidationResult: - r"""Gets the latest flow validation result. Flow - validation is performed when ValidateFlow is called. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetFlowValidationResultRequest): - The request object. The request message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. - name (str): - Required. The flow name. Format: - ``projects//locations//agents//flows//validationResult``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.FlowValidationResult: - The response message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 flow.GetFlowValidationResultRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.GetFlowValidationResultRequest): - request = flow.GetFlowValidationResultRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_flow_validation_result] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_flow(self, - request: flow.ImportFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Imports the specified flow to the specified agent - from a binary file. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest): - The request object. The request message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.ImportFlowResponse` - The response message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a flow.ImportFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.ImportFlowRequest): - request = flow.ImportFlowRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - flow.ImportFlowResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - def export_flow(self, - request: flow.ExportFlowRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ExportFlowRequest): - The request object. The request message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowResponse` - The response message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a flow.ExportFlowRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, flow.ExportFlowRequest): - request = flow.ExportFlowRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_flow] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - flow.ExportFlowResponse, - metadata_type=struct_pb2.Struct, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "FlowsClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py deleted file mode 100644 index c1e7bc19..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/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.dialogflowcx_v3beta1.types import flow - - -class ListFlowsPager: - """A pager for iterating through ``list_flows`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``flows`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFlows`` requests and continue to iterate - through the ``flows`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse` - 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[..., flow.ListFlowsResponse], - request: flow.ListFlowsRequest, - response: flow.ListFlowsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListFlowsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse): - 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 = flow.ListFlowsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[flow.ListFlowsResponse]: - 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[flow.Flow]: - for page in self.pages: - yield from page.flows - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFlowsAsyncPager: - """A pager for iterating through ``list_flows`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``flows`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFlows`` requests and continue to iterate - through the ``flows`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse` - 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[flow.ListFlowsResponse]], - request: flow.ListFlowsRequest, - response: flow.ListFlowsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListFlowsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListFlowsResponse): - 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 = flow.ListFlowsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[flow.ListFlowsResponse]: - 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[flow.Flow]: - async def async_generator(): - async for page in self.pages: - for response in page.flows: - 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py deleted file mode 100644 index 4ba28aff..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/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 FlowsTransport -from .grpc import FlowsGrpcTransport -from .grpc_asyncio import FlowsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[FlowsTransport]] -_transport_registry['grpc'] = FlowsGrpcTransport -_transport_registry['grpc_asyncio'] = FlowsGrpcAsyncIOTransport - -__all__ = ( - 'FlowsTransport', - 'FlowsGrpcTransport', - 'FlowsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py deleted file mode 100644 index 1afa01a6..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/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.dialogflowcx_v3beta1.types import flow -from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow -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-dialogflowcx', - ).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 FlowsTransport(abc.ABC): - """Abstract transport class for Flows.""" - - 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_flow: gapic_v1.method.wrap_method( - self.create_flow, - default_timeout=None, - client_info=client_info, - ), - self.delete_flow: gapic_v1.method.wrap_method( - self.delete_flow, - default_timeout=None, - client_info=client_info, - ), - self.list_flows: gapic_v1.method.wrap_method( - self.list_flows, - default_timeout=None, - client_info=client_info, - ), - self.get_flow: gapic_v1.method.wrap_method( - self.get_flow, - default_timeout=None, - client_info=client_info, - ), - self.update_flow: gapic_v1.method.wrap_method( - self.update_flow, - default_timeout=None, - client_info=client_info, - ), - self.train_flow: gapic_v1.method.wrap_method( - self.train_flow, - default_timeout=None, - client_info=client_info, - ), - self.validate_flow: gapic_v1.method.wrap_method( - self.validate_flow, - default_timeout=None, - client_info=client_info, - ), - self.get_flow_validation_result: gapic_v1.method.wrap_method( - self.get_flow_validation_result, - default_timeout=None, - client_info=client_info, - ), - self.import_flow: gapic_v1.method.wrap_method( - self.import_flow, - default_timeout=None, - client_info=client_info, - ), - self.export_flow: gapic_v1.method.wrap_method( - self.export_flow, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_flow(self) -> Callable[ - [gcdc_flow.CreateFlowRequest], - Union[ - gcdc_flow.Flow, - Awaitable[gcdc_flow.Flow] - ]]: - raise NotImplementedError() - - @property - def delete_flow(self) -> Callable[ - [flow.DeleteFlowRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_flows(self) -> Callable[ - [flow.ListFlowsRequest], - Union[ - flow.ListFlowsResponse, - Awaitable[flow.ListFlowsResponse] - ]]: - raise NotImplementedError() - - @property - def get_flow(self) -> Callable[ - [flow.GetFlowRequest], - Union[ - flow.Flow, - Awaitable[flow.Flow] - ]]: - raise NotImplementedError() - - @property - def update_flow(self) -> Callable[ - [gcdc_flow.UpdateFlowRequest], - Union[ - gcdc_flow.Flow, - Awaitable[gcdc_flow.Flow] - ]]: - raise NotImplementedError() - - @property - def train_flow(self) -> Callable[ - [flow.TrainFlowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def validate_flow(self) -> Callable[ - [flow.ValidateFlowRequest], - Union[ - flow.FlowValidationResult, - Awaitable[flow.FlowValidationResult] - ]]: - raise NotImplementedError() - - @property - def get_flow_validation_result(self) -> Callable[ - [flow.GetFlowValidationResultRequest], - Union[ - flow.FlowValidationResult, - Awaitable[flow.FlowValidationResult] - ]]: - raise NotImplementedError() - - @property - def import_flow(self) -> Callable[ - [flow.ImportFlowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_flow(self) -> Callable[ - [flow.ExportFlowRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'FlowsTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py deleted file mode 100644 index 2eae3bee..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import flow -from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import FlowsTransport, DEFAULT_CLIENT_INFO - - -class FlowsGrpcTransport(FlowsTransport): - """gRPC backend transport for Flows. - - Service for managing - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow]. - - 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 create_flow(self) -> Callable[ - [gcdc_flow.CreateFlowRequest], - gcdc_flow.Flow]: - r"""Return a callable for the create flow method over gRPC. - - Creates a flow in the specified agent. - - Returns: - Callable[[~.CreateFlowRequest], - ~.Flow]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_flow' not in self._stubs: - self._stubs['create_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/CreateFlow', - request_serializer=gcdc_flow.CreateFlowRequest.serialize, - response_deserializer=gcdc_flow.Flow.deserialize, - ) - return self._stubs['create_flow'] - - @property - def delete_flow(self) -> Callable[ - [flow.DeleteFlowRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete flow method over gRPC. - - Deletes a specified flow. - - Returns: - Callable[[~.DeleteFlowRequest], - ~.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_flow' not in self._stubs: - self._stubs['delete_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/DeleteFlow', - request_serializer=flow.DeleteFlowRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_flow'] - - @property - def list_flows(self) -> Callable[ - [flow.ListFlowsRequest], - flow.ListFlowsResponse]: - r"""Return a callable for the list flows method over gRPC. - - Returns the list of all flows in the specified agent. - - Returns: - Callable[[~.ListFlowsRequest], - ~.ListFlowsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_flows' not in self._stubs: - self._stubs['list_flows'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/ListFlows', - request_serializer=flow.ListFlowsRequest.serialize, - response_deserializer=flow.ListFlowsResponse.deserialize, - ) - return self._stubs['list_flows'] - - @property - def get_flow(self) -> Callable[ - [flow.GetFlowRequest], - flow.Flow]: - r"""Return a callable for the get flow method over gRPC. - - Retrieves the specified flow. - - Returns: - Callable[[~.GetFlowRequest], - ~.Flow]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_flow' not in self._stubs: - self._stubs['get_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/GetFlow', - request_serializer=flow.GetFlowRequest.serialize, - response_deserializer=flow.Flow.deserialize, - ) - return self._stubs['get_flow'] - - @property - def update_flow(self) -> Callable[ - [gcdc_flow.UpdateFlowRequest], - gcdc_flow.Flow]: - r"""Return a callable for the update flow method over gRPC. - - Updates the specified flow. - - Returns: - Callable[[~.UpdateFlowRequest], - ~.Flow]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_flow' not in self._stubs: - self._stubs['update_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/UpdateFlow', - request_serializer=gcdc_flow.UpdateFlowRequest.serialize, - response_deserializer=gcdc_flow.Flow.deserialize, - ) - return self._stubs['update_flow'] - - @property - def train_flow(self) -> Callable[ - [flow.TrainFlowRequest], - operations_pb2.Operation]: - r"""Return a callable for the train flow method over gRPC. - - Trains the specified flow. Note that only the flow in - 'draft' environment is trained. - - Returns: - Callable[[~.TrainFlowRequest], - ~.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_flow' not in self._stubs: - self._stubs['train_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/TrainFlow', - request_serializer=flow.TrainFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_flow'] - - @property - def validate_flow(self) -> Callable[ - [flow.ValidateFlowRequest], - flow.FlowValidationResult]: - r"""Return a callable for the validate flow method over gRPC. - - Validates the specified flow and creates or updates - validation results. Please call this API after the - training is completed to get the complete validation - results. - - Returns: - Callable[[~.ValidateFlowRequest], - ~.FlowValidationResult]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_flow' not in self._stubs: - self._stubs['validate_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/ValidateFlow', - request_serializer=flow.ValidateFlowRequest.serialize, - response_deserializer=flow.FlowValidationResult.deserialize, - ) - return self._stubs['validate_flow'] - - @property - def get_flow_validation_result(self) -> Callable[ - [flow.GetFlowValidationResultRequest], - flow.FlowValidationResult]: - r"""Return a callable for the get flow validation result method over gRPC. - - Gets the latest flow validation result. Flow - validation is performed when ValidateFlow is called. - - Returns: - Callable[[~.GetFlowValidationResultRequest], - ~.FlowValidationResult]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_flow_validation_result' not in self._stubs: - self._stubs['get_flow_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/GetFlowValidationResult', - request_serializer=flow.GetFlowValidationResultRequest.serialize, - response_deserializer=flow.FlowValidationResult.deserialize, - ) - return self._stubs['get_flow_validation_result'] - - @property - def import_flow(self) -> Callable[ - [flow.ImportFlowRequest], - operations_pb2.Operation]: - r"""Return a callable for the import flow method over gRPC. - - Imports the specified flow to the specified agent - from a binary file. - - Returns: - Callable[[~.ImportFlowRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_flow' not in self._stubs: - self._stubs['import_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/ImportFlow', - request_serializer=flow.ImportFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_flow'] - - @property - def export_flow(self) -> Callable[ - [flow.ExportFlowRequest], - operations_pb2.Operation]: - r"""Return a callable for the export flow method over gRPC. - - Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. - - Returns: - Callable[[~.ExportFlowRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_flow' not in self._stubs: - self._stubs['export_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/ExportFlow', - request_serializer=flow.ExportFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_flow'] - - -__all__ = ( - 'FlowsGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py deleted file mode 100644 index b038bb29..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py +++ /dev/null @@ -1,516 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import flow -from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import FlowsTransport, DEFAULT_CLIENT_INFO -from .grpc import FlowsGrpcTransport - - -class FlowsGrpcAsyncIOTransport(FlowsTransport): - """gRPC AsyncIO backend transport for Flows. - - Service for managing - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow]. - - 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 create_flow(self) -> Callable[ - [gcdc_flow.CreateFlowRequest], - Awaitable[gcdc_flow.Flow]]: - r"""Return a callable for the create flow method over gRPC. - - Creates a flow in the specified agent. - - Returns: - Callable[[~.CreateFlowRequest], - Awaitable[~.Flow]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_flow' not in self._stubs: - self._stubs['create_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/CreateFlow', - request_serializer=gcdc_flow.CreateFlowRequest.serialize, - response_deserializer=gcdc_flow.Flow.deserialize, - ) - return self._stubs['create_flow'] - - @property - def delete_flow(self) -> Callable[ - [flow.DeleteFlowRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete flow method over gRPC. - - Deletes a specified flow. - - Returns: - Callable[[~.DeleteFlowRequest], - 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_flow' not in self._stubs: - self._stubs['delete_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/DeleteFlow', - request_serializer=flow.DeleteFlowRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_flow'] - - @property - def list_flows(self) -> Callable[ - [flow.ListFlowsRequest], - Awaitable[flow.ListFlowsResponse]]: - r"""Return a callable for the list flows method over gRPC. - - Returns the list of all flows in the specified agent. - - Returns: - Callable[[~.ListFlowsRequest], - Awaitable[~.ListFlowsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_flows' not in self._stubs: - self._stubs['list_flows'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/ListFlows', - request_serializer=flow.ListFlowsRequest.serialize, - response_deserializer=flow.ListFlowsResponse.deserialize, - ) - return self._stubs['list_flows'] - - @property - def get_flow(self) -> Callable[ - [flow.GetFlowRequest], - Awaitable[flow.Flow]]: - r"""Return a callable for the get flow method over gRPC. - - Retrieves the specified flow. - - Returns: - Callable[[~.GetFlowRequest], - Awaitable[~.Flow]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_flow' not in self._stubs: - self._stubs['get_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/GetFlow', - request_serializer=flow.GetFlowRequest.serialize, - response_deserializer=flow.Flow.deserialize, - ) - return self._stubs['get_flow'] - - @property - def update_flow(self) -> Callable[ - [gcdc_flow.UpdateFlowRequest], - Awaitable[gcdc_flow.Flow]]: - r"""Return a callable for the update flow method over gRPC. - - Updates the specified flow. - - Returns: - Callable[[~.UpdateFlowRequest], - Awaitable[~.Flow]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_flow' not in self._stubs: - self._stubs['update_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/UpdateFlow', - request_serializer=gcdc_flow.UpdateFlowRequest.serialize, - response_deserializer=gcdc_flow.Flow.deserialize, - ) - return self._stubs['update_flow'] - - @property - def train_flow(self) -> Callable[ - [flow.TrainFlowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the train flow method over gRPC. - - Trains the specified flow. Note that only the flow in - 'draft' environment is trained. - - Returns: - Callable[[~.TrainFlowRequest], - 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_flow' not in self._stubs: - self._stubs['train_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/TrainFlow', - request_serializer=flow.TrainFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['train_flow'] - - @property - def validate_flow(self) -> Callable[ - [flow.ValidateFlowRequest], - Awaitable[flow.FlowValidationResult]]: - r"""Return a callable for the validate flow method over gRPC. - - Validates the specified flow and creates or updates - validation results. Please call this API after the - training is completed to get the complete validation - results. - - Returns: - Callable[[~.ValidateFlowRequest], - Awaitable[~.FlowValidationResult]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'validate_flow' not in self._stubs: - self._stubs['validate_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/ValidateFlow', - request_serializer=flow.ValidateFlowRequest.serialize, - response_deserializer=flow.FlowValidationResult.deserialize, - ) - return self._stubs['validate_flow'] - - @property - def get_flow_validation_result(self) -> Callable[ - [flow.GetFlowValidationResultRequest], - Awaitable[flow.FlowValidationResult]]: - r"""Return a callable for the get flow validation result method over gRPC. - - Gets the latest flow validation result. Flow - validation is performed when ValidateFlow is called. - - Returns: - Callable[[~.GetFlowValidationResultRequest], - Awaitable[~.FlowValidationResult]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_flow_validation_result' not in self._stubs: - self._stubs['get_flow_validation_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/GetFlowValidationResult', - request_serializer=flow.GetFlowValidationResultRequest.serialize, - response_deserializer=flow.FlowValidationResult.deserialize, - ) - return self._stubs['get_flow_validation_result'] - - @property - def import_flow(self) -> Callable[ - [flow.ImportFlowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import flow method over gRPC. - - Imports the specified flow to the specified agent - from a binary file. - - Returns: - Callable[[~.ImportFlowRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_flow' not in self._stubs: - self._stubs['import_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/ImportFlow', - request_serializer=flow.ImportFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_flow'] - - @property - def export_flow(self) -> Callable[ - [flow.ExportFlowRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the export flow method over gRPC. - - Exports the specified flow to a binary file. - Note that resources (e.g. intents, entities, webhooks) - that the flow references will also be exported. - - Returns: - Callable[[~.ExportFlowRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'export_flow' not in self._stubs: - self._stubs['export_flow'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Flows/ExportFlow', - request_serializer=flow.ExportFlowRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_flow'] - - -__all__ = ( - 'FlowsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py deleted file mode 100644 index 8204500f..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py deleted file mode 100644 index eee35c82..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py +++ /dev/null @@ -1,580 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.intents import pagers -from google.cloud.dialogflowcx_v3beta1.types import intent -from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -from google.protobuf import field_mask_pb2 # 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.cx.v3beta1.Intent]. - """ - - _client: IntentsClient - - DEFAULT_ENDPOINT = IntentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = IntentsClient.DEFAULT_MTLS_ENDPOINT - - entity_type_path = staticmethod(IntentsClient.entity_type_path) - parse_entity_type_path = staticmethod(IntentsClient.parse_entity_type_path) - intent_path = staticmethod(IntentsClient.intent_path) - parse_intent_path = staticmethod(IntentsClient.parse_intent_path) - common_billing_account_path = staticmethod(IntentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(IntentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(IntentsClient.common_folder_path) - parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) - common_organization_path = staticmethod(IntentsClient.common_organization_path) - parse_common_organization_path = staticmethod(IntentsClient.parse_common_organization_path) - common_project_path = staticmethod(IntentsClient.common_project_path) - parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) - common_location_path = staticmethod(IntentsClient.common_location_path) - parse_common_location_path = staticmethod(IntentsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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, - 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.dialogflowcx_v3beta1.types.ListIntentsRequest`): - The request object. The request message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.Intents.ListIntents]. - parent (:class:`str`): - Required. The agent to list all intents for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.intents.pagers.ListIntentsAsyncPager: - The response message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.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]) - if request is not 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 - - # 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, - 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.dialogflowcx_v3beta1.types.GetIntentRequest`): - The request object. The request message for - [Intents.GetIntent][google.cloud.dialogflow.cx.v3beta1.Intents.GetIntent]. - name (:class:`str`): - Required. The name of the intent. Format: - ``projects//locations//agents//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. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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.GetIntentRequest(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_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: gcdc_intent.CreateIntentRequest = None, - *, - parent: str = None, - intent: gcdc_intent.Intent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_intent.Intent: - r"""Creates an intent in the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateIntentRequest`): - The request object. The request message for - [Intents.CreateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.CreateIntent]. - parent (:class:`str`): - Required. The agent to create an intent for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent (:class:`google.cloud.dialogflowcx_v3beta1.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. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_intent.CreateIntentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if intent is not None: - request.intent = intent - - # 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: gcdc_intent.UpdateIntentRequest = None, - *, - intent: gcdc_intent.Intent = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_intent.Intent: - r"""Updates the specified intent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateIntentRequest`): - The request object. The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.UpdateIntent]. - intent (:class:`google.cloud.dialogflowcx_v3beta1.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`): - 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.dialogflowcx_v3beta1.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity 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]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_intent.UpdateIntentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if intent is not None: - request.intent = intent - if update_mask is not None: - 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. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteIntentRequest`): - The request object. The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3beta1.Intents.DeleteIntent]. - name (:class:`str`): - Required. The name of the intent to delete. Format: - ``projects//locations//agents//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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "IntentsAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/client.py deleted file mode 100644 index 81957c73..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/client.py +++ /dev/null @@ -1,776 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.intents import pagers -from google.cloud.dialogflowcx_v3beta1.types import intent -from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -from google.protobuf import field_mask_pb2 # 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.cx.v3beta1.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 entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/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, - 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.dialogflowcx_v3beta1.types.ListIntentsRequest): - The request object. The request message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.Intents.ListIntents]. - parent (str): - Required. The agent to list all intents for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.intents.pagers.ListIntentsPager: - The response message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is 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 - - # 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, - 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.dialogflowcx_v3beta1.types.GetIntentRequest): - The request object. The request message for - [Intents.GetIntent][google.cloud.dialogflow.cx.v3beta1.Intents.GetIntent]. - name (str): - Required. The name of the intent. Format: - ``projects//locations//agents//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. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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.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 - - # 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: gcdc_intent.CreateIntentRequest = None, - *, - parent: str = None, - intent: gcdc_intent.Intent = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_intent.Intent: - r"""Creates an intent in the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateIntentRequest): - The request object. The request message for - [Intents.CreateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.CreateIntent]. - parent (str): - Required. The agent to create an intent for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - intent (google.cloud.dialogflowcx_v3beta1.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. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_intent.CreateIntentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_intent.CreateIntentRequest): - request = gcdc_intent.CreateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if intent is not None: - request.intent = intent - - # 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: gcdc_intent.UpdateIntentRequest = None, - *, - intent: gcdc_intent.Intent = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_intent.Intent: - r"""Updates the specified intent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateIntentRequest): - The request object. The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.UpdateIntent]. - intent (google.cloud.dialogflowcx_v3beta1.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): - 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.dialogflowcx_v3beta1.types.Intent: - An intent represents a user's intent - to interact with a conversational agent. - You can provide information for the - Dialogflow API to use to match user - input to an intent by adding training - phrases (i.e., examples of user input) - to your intent. - - """ - # Create or coerce a protobuf request object. - # Sanity 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_intent.UpdateIntentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_intent.UpdateIntentRequest): - request = gcdc_intent.UpdateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if intent is not None: - request.intent = intent - if update_mask is not None: - 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. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.DeleteIntentRequest): - The request object. The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3beta1.Intents.DeleteIntent]. - name (str): - Required. The name of the intent to delete. Format: - ``projects//locations//agents//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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "IntentsClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py deleted file mode 100644 index ab57eb74..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.types import intent - - -class ListIntentsPager: - """A pager for iterating through ``list_intents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListIntentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListIntentsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py deleted file mode 100644 index aa8039bb..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py deleted file mode 100644 index 46d79381..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/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.dialogflowcx_v3beta1.types import intent -from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -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-dialogflowcx', - ).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, - ), - } - - @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[ - [gcdc_intent.CreateIntentRequest], - Union[ - gcdc_intent.Intent, - Awaitable[gcdc_intent.Intent] - ]]: - raise NotImplementedError() - - @property - def update_intent(self) -> Callable[ - [gcdc_intent.UpdateIntentRequest], - Union[ - gcdc_intent.Intent, - Awaitable[gcdc_intent.Intent] - ]]: - raise NotImplementedError() - - @property - def delete_intent(self) -> Callable[ - [intent.DeleteIntentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'IntentsTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py deleted file mode 100644 index feeddaf7..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/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.dialogflowcx_v3beta1.types import intent -from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -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.cx.v3beta1.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] = {} - - 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_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.cx.v3beta1.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.cx.v3beta1.Intents/GetIntent', - request_serializer=intent.GetIntentRequest.serialize, - response_deserializer=intent.Intent.deserialize, - ) - return self._stubs['get_intent'] - - @property - def create_intent(self) -> Callable[ - [gcdc_intent.CreateIntentRequest], - gcdc_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.cx.v3beta1.Intents/CreateIntent', - request_serializer=gcdc_intent.CreateIntentRequest.serialize, - response_deserializer=gcdc_intent.Intent.deserialize, - ) - return self._stubs['create_intent'] - - @property - def update_intent(self) -> Callable[ - [gcdc_intent.UpdateIntentRequest], - gcdc_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.cx.v3beta1.Intents/UpdateIntent', - request_serializer=gcdc_intent.UpdateIntentRequest.serialize, - response_deserializer=gcdc_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. - - 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.cx.v3beta1.Intents/DeleteIntent', - request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_intent'] - - -__all__ = ( - 'IntentsGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py deleted file mode 100644 index 776d967c..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/intents/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.dialogflowcx_v3beta1.types import intent -from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -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.cx.v3beta1.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] = {} - - 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_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.cx.v3beta1.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.cx.v3beta1.Intents/GetIntent', - request_serializer=intent.GetIntentRequest.serialize, - response_deserializer=intent.Intent.deserialize, - ) - return self._stubs['get_intent'] - - @property - def create_intent(self) -> Callable[ - [gcdc_intent.CreateIntentRequest], - Awaitable[gcdc_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.cx.v3beta1.Intents/CreateIntent', - request_serializer=gcdc_intent.CreateIntentRequest.serialize, - response_deserializer=gcdc_intent.Intent.deserialize, - ) - return self._stubs['create_intent'] - - @property - def update_intent(self) -> Callable[ - [gcdc_intent.UpdateIntentRequest], - Awaitable[gcdc_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.cx.v3beta1.Intents/UpdateIntent', - request_serializer=gcdc_intent.UpdateIntentRequest.serialize, - response_deserializer=gcdc_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. - - 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.cx.v3beta1.Intents/DeleteIntent', - request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_intent'] - - -__all__ = ( - 'IntentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py deleted file mode 100644 index b8668f72..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/__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 PagesClient -from .async_client import PagesAsyncClient - -__all__ = ( - 'PagesClient', - 'PagesAsyncClient', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py deleted file mode 100644 index bf55f0a9..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py +++ /dev/null @@ -1,633 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.pages import pagers -from google.cloud.dialogflowcx_v3beta1.types import fulfillment -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport -from .client import PagesClient - - -class PagesAsyncClient: - """Service for managing - [Pages][google.cloud.dialogflow.cx.v3beta1.Page]. - """ - - _client: PagesClient - - DEFAULT_ENDPOINT = PagesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PagesClient.DEFAULT_MTLS_ENDPOINT - - entity_type_path = staticmethod(PagesClient.entity_type_path) - parse_entity_type_path = staticmethod(PagesClient.parse_entity_type_path) - flow_path = staticmethod(PagesClient.flow_path) - parse_flow_path = staticmethod(PagesClient.parse_flow_path) - intent_path = staticmethod(PagesClient.intent_path) - parse_intent_path = staticmethod(PagesClient.parse_intent_path) - page_path = staticmethod(PagesClient.page_path) - parse_page_path = staticmethod(PagesClient.parse_page_path) - transition_route_group_path = staticmethod(PagesClient.transition_route_group_path) - parse_transition_route_group_path = staticmethod(PagesClient.parse_transition_route_group_path) - webhook_path = staticmethod(PagesClient.webhook_path) - parse_webhook_path = staticmethod(PagesClient.parse_webhook_path) - common_billing_account_path = staticmethod(PagesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PagesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PagesClient.common_folder_path) - parse_common_folder_path = staticmethod(PagesClient.parse_common_folder_path) - common_organization_path = staticmethod(PagesClient.common_organization_path) - parse_common_organization_path = staticmethod(PagesClient.parse_common_organization_path) - common_project_path = staticmethod(PagesClient.common_project_path) - parse_common_project_path = staticmethod(PagesClient.parse_common_project_path) - common_location_path = staticmethod(PagesClient.common_location_path) - parse_common_location_path = staticmethod(PagesClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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: - PagesAsyncClient: The constructed client. - """ - return PagesClient.from_service_account_info.__func__(PagesAsyncClient, 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: - PagesAsyncClient: The constructed client. - """ - return PagesClient.from_service_account_file.__func__(PagesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> PagesTransport: - """Returns the transport used by the client instance. - - Returns: - PagesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(PagesClient).get_transport_class, type(PagesClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, PagesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the pages 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, ~.PagesTransport]): 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 = PagesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_pages(self, - request: page.ListPagesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPagesAsyncPager: - r"""Returns the list of all pages in the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesRequest`): - The request object. The request message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. - parent (:class:`str`): - Required. The flow to list all pages for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.pages.pagers.ListPagesAsyncPager: - The response message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. - - 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 = page.ListPagesRequest(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_pages, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListPagesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_page(self, - request: page.GetPageRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> page.Page: - r"""Retrieves the specified page. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetPageRequest`): - The request object. The request message for - [Pages.GetPage][google.cloud.dialogflow.cx.v3beta1.Pages.GetPage]. - name (:class:`str`): - Required. The name of the page. Format: - ``projects//locations//agents//flows//pages/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = page.GetPageRequest(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_page, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_page(self, - request: gcdc_page.CreatePageRequest = None, - *, - parent: str = None, - page: gcdc_page.Page = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_page.Page: - r"""Creates a page in the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreatePageRequest`): - The request object. The request message for - [Pages.CreatePage][google.cloud.dialogflow.cx.v3beta1.Pages.CreatePage]. - parent (:class:`str`): - Required. The flow to create a page for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - page (:class:`google.cloud.dialogflowcx_v3beta1.types.Page`): - Required. The page to create. - This corresponds to the ``page`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, page]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_page.CreatePageRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if page is not None: - request.page = page - - # 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_page, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_page(self, - request: gcdc_page.UpdatePageRequest = None, - *, - page: gcdc_page.Page = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_page.Page: - r"""Updates the specified page. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdatePageRequest`): - The request object. The request message for - [Pages.UpdatePage][google.cloud.dialogflow.cx.v3beta1.Pages.UpdatePage]. - page (:class:`google.cloud.dialogflowcx_v3beta1.types.Page`): - Required. The page to update. - This corresponds to the ``page`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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.dialogflowcx_v3beta1.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([page, 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 = gcdc_page.UpdatePageRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if page is not None: - request.page = page - if update_mask is not None: - 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_page, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("page.name", request.page.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_page(self, - request: page.DeletePageRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified page. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeletePageRequest`): - The request object. The request message for - [Pages.DeletePage][google.cloud.dialogflow.cx.v3beta1.Pages.DeletePage]. - name (:class:`str`): - Required. The name of the page to delete. Format: - ``projects//locations//agents//Flows//pages/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = page.DeletePageRequest(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_page, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PagesAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/client.py deleted file mode 100644 index 600b018a..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/client.py +++ /dev/null @@ -1,865 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.pages import pagers -from google.cloud.dialogflowcx_v3beta1.types import fulfillment -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PagesGrpcTransport -from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport - - -class PagesClientMeta(type): - """Metaclass for the Pages 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[PagesTransport]] - _transport_registry["grpc"] = PagesGrpcTransport - _transport_registry["grpc_asyncio"] = PagesGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[PagesTransport]: - """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 PagesClient(metaclass=PagesClientMeta): - """Service for managing - [Pages][google.cloud.dialogflow.cx.v3beta1.Page]. - """ - - @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: - PagesClient: 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: - PagesClient: 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) -> PagesTransport: - """Returns the transport used by the client instance. - - Returns: - PagesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: - """Returns a fully-qualified page string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - - @staticmethod - def parse_page_path(path: str) -> Dict[str,str]: - """Parses a page path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: - """Returns a fully-qualified transition_route_group string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - - @staticmethod - def parse_transition_route_group_path(path: str) -> Dict[str,str]: - """Parses a transition_route_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, PagesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the pages 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, PagesTransport]): 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, PagesTransport): - # transport is a PagesTransport 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_pages(self, - request: page.ListPagesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListPagesPager: - r"""Returns the list of all pages in the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListPagesRequest): - The request object. The request message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. - parent (str): - Required. The flow to list all pages for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.pages.pagers.ListPagesPager: - The response message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. - - 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 page.ListPagesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, page.ListPagesRequest): - request = page.ListPagesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_pages] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListPagesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_page(self, - request: page.GetPageRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> page.Page: - r"""Retrieves the specified page. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetPageRequest): - The request object. The request message for - [Pages.GetPage][google.cloud.dialogflow.cx.v3beta1.Pages.GetPage]. - name (str): - Required. The name of the page. Format: - ``projects//locations//agents//flows//pages/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 page.GetPageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, page.GetPageRequest): - request = page.GetPageRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_page] - - # Certain fields should be provided 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_page(self, - request: gcdc_page.CreatePageRequest = None, - *, - parent: str = None, - page: gcdc_page.Page = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_page.Page: - r"""Creates a page in the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreatePageRequest): - The request object. The request message for - [Pages.CreatePage][google.cloud.dialogflow.cx.v3beta1.Pages.CreatePage]. - parent (str): - Required. The flow to create a page for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - page (google.cloud.dialogflowcx_v3beta1.types.Page): - Required. The page to create. - This corresponds to the ``page`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, page]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_page.CreatePageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_page.CreatePageRequest): - request = gcdc_page.CreatePageRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if page is not None: - request.page = page - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_page] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_page(self, - request: gcdc_page.UpdatePageRequest = None, - *, - page: gcdc_page.Page = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_page.Page: - r"""Updates the specified page. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdatePageRequest): - The request object. The request message for - [Pages.UpdatePage][google.cloud.dialogflow.cx.v3beta1.Pages.UpdatePage]. - page (google.cloud.dialogflowcx_v3beta1.types.Page): - Required. The page to update. - This corresponds to the ``page`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.dialogflowcx_v3beta1.types.Page: - A Dialogflow CX conversation (session) can be described and visualized as a - state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your - combined pages can handle a complete conversation on - the topics the flow is designed for. At any given - moment, exactly one page is the current page, the - current page is considered active, and the flow - associated with that page is considered active. Every - flow has a special start page. When a flow initially - becomes active, the start page page becomes the - current page. For each conversational turn, the - current page will either stay the same or transition - to another page. - - You configure each page to collect information from - the end-user that is relevant for the conversational - state represented by the page. - - For more information, see the [Page - guide](\ https://cloud.google.com/dialogflow/cx/docs/concept/page). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([page, 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 gcdc_page.UpdatePageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_page.UpdatePageRequest): - request = gcdc_page.UpdatePageRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if page is not None: - request.page = page - if update_mask is not None: - 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_page] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("page.name", request.page.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_page(self, - request: page.DeletePageRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified page. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.DeletePageRequest): - The request object. The request message for - [Pages.DeletePage][google.cloud.dialogflow.cx.v3beta1.Pages.DeletePage]. - name (str): - Required. The name of the page to delete. Format: - ``projects//locations//agents//Flows//pages/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 page.DeletePageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, page.DeletePageRequest): - request = page.DeletePageRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_page] - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "PagesClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py deleted file mode 100644 index 974940d5..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/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.dialogflowcx_v3beta1.types import page - - -class ListPagesPager: - """A pager for iterating through ``list_pages`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``pages`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPages`` requests and continue to iterate - through the ``pages`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse` - 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[..., page.ListPagesResponse], - request: page.ListPagesRequest, - response: page.ListPagesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListPagesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse): - 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 = page.ListPagesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[page.ListPagesResponse]: - 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[page.Page]: - for page in self.pages: - yield from page.pages - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPagesAsyncPager: - """A pager for iterating through ``list_pages`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``pages`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPages`` requests and continue to iterate - through the ``pages`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse` - 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[page.ListPagesResponse]], - request: page.ListPagesRequest, - response: page.ListPagesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListPagesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListPagesResponse): - 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 = page.ListPagesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[page.ListPagesResponse]: - 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[page.Page]: - async def async_generator(): - async for page in self.pages: - for response in page.pages: - 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py deleted file mode 100644 index ee74f029..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/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 PagesTransport -from .grpc import PagesGrpcTransport -from .grpc_asyncio import PagesGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PagesTransport]] -_transport_registry['grpc'] = PagesGrpcTransport -_transport_registry['grpc_asyncio'] = PagesGrpcAsyncIOTransport - -__all__ = ( - 'PagesTransport', - 'PagesGrpcTransport', - 'PagesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py deleted file mode 100644 index ee8147bf..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/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.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page -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-dialogflowcx', - ).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 PagesTransport(abc.ABC): - """Abstract transport class for Pages.""" - - 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_pages: gapic_v1.method.wrap_method( - self.list_pages, - default_timeout=None, - client_info=client_info, - ), - self.get_page: gapic_v1.method.wrap_method( - self.get_page, - default_timeout=None, - client_info=client_info, - ), - self.create_page: gapic_v1.method.wrap_method( - self.create_page, - default_timeout=None, - client_info=client_info, - ), - self.update_page: gapic_v1.method.wrap_method( - self.update_page, - default_timeout=None, - client_info=client_info, - ), - self.delete_page: gapic_v1.method.wrap_method( - self.delete_page, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_pages(self) -> Callable[ - [page.ListPagesRequest], - Union[ - page.ListPagesResponse, - Awaitable[page.ListPagesResponse] - ]]: - raise NotImplementedError() - - @property - def get_page(self) -> Callable[ - [page.GetPageRequest], - Union[ - page.Page, - Awaitable[page.Page] - ]]: - raise NotImplementedError() - - @property - def create_page(self) -> Callable[ - [gcdc_page.CreatePageRequest], - Union[ - gcdc_page.Page, - Awaitable[gcdc_page.Page] - ]]: - raise NotImplementedError() - - @property - def update_page(self) -> Callable[ - [gcdc_page.UpdatePageRequest], - Union[ - gcdc_page.Page, - Awaitable[gcdc_page.Page] - ]]: - raise NotImplementedError() - - @property - def delete_page(self) -> Callable[ - [page.DeletePageRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'PagesTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py deleted file mode 100644 index 2f85f709..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py +++ /dev/null @@ -1,355 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page -from google.protobuf import empty_pb2 # type: ignore -from .base import PagesTransport, DEFAULT_CLIENT_INFO - - -class PagesGrpcTransport(PagesTransport): - """gRPC backend transport for Pages. - - Service for managing - [Pages][google.cloud.dialogflow.cx.v3beta1.Page]. - - 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_pages(self) -> Callable[ - [page.ListPagesRequest], - page.ListPagesResponse]: - r"""Return a callable for the list pages method over gRPC. - - Returns the list of all pages in the specified flow. - - Returns: - Callable[[~.ListPagesRequest], - ~.ListPagesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_pages' not in self._stubs: - self._stubs['list_pages'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Pages/ListPages', - request_serializer=page.ListPagesRequest.serialize, - response_deserializer=page.ListPagesResponse.deserialize, - ) - return self._stubs['list_pages'] - - @property - def get_page(self) -> Callable[ - [page.GetPageRequest], - page.Page]: - r"""Return a callable for the get page method over gRPC. - - Retrieves the specified page. - - Returns: - Callable[[~.GetPageRequest], - ~.Page]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_page' not in self._stubs: - self._stubs['get_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Pages/GetPage', - request_serializer=page.GetPageRequest.serialize, - response_deserializer=page.Page.deserialize, - ) - return self._stubs['get_page'] - - @property - def create_page(self) -> Callable[ - [gcdc_page.CreatePageRequest], - gcdc_page.Page]: - r"""Return a callable for the create page method over gRPC. - - Creates a page in the specified flow. - - Returns: - Callable[[~.CreatePageRequest], - ~.Page]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_page' not in self._stubs: - self._stubs['create_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Pages/CreatePage', - request_serializer=gcdc_page.CreatePageRequest.serialize, - response_deserializer=gcdc_page.Page.deserialize, - ) - return self._stubs['create_page'] - - @property - def update_page(self) -> Callable[ - [gcdc_page.UpdatePageRequest], - gcdc_page.Page]: - r"""Return a callable for the update page method over gRPC. - - Updates the specified page. - - Returns: - Callable[[~.UpdatePageRequest], - ~.Page]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_page' not in self._stubs: - self._stubs['update_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Pages/UpdatePage', - request_serializer=gcdc_page.UpdatePageRequest.serialize, - response_deserializer=gcdc_page.Page.deserialize, - ) - return self._stubs['update_page'] - - @property - def delete_page(self) -> Callable[ - [page.DeletePageRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete page method over gRPC. - - Deletes the specified page. - - Returns: - Callable[[~.DeletePageRequest], - ~.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_page' not in self._stubs: - self._stubs['delete_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Pages/DeletePage', - request_serializer=page.DeletePageRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_page'] - - -__all__ = ( - 'PagesGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py deleted file mode 100644 index cc5e44df..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py +++ /dev/null @@ -1,359 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page -from google.protobuf import empty_pb2 # type: ignore -from .base import PagesTransport, DEFAULT_CLIENT_INFO -from .grpc import PagesGrpcTransport - - -class PagesGrpcAsyncIOTransport(PagesTransport): - """gRPC AsyncIO backend transport for Pages. - - Service for managing - [Pages][google.cloud.dialogflow.cx.v3beta1.Page]. - - 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_pages(self) -> Callable[ - [page.ListPagesRequest], - Awaitable[page.ListPagesResponse]]: - r"""Return a callable for the list pages method over gRPC. - - Returns the list of all pages in the specified flow. - - Returns: - Callable[[~.ListPagesRequest], - Awaitable[~.ListPagesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_pages' not in self._stubs: - self._stubs['list_pages'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Pages/ListPages', - request_serializer=page.ListPagesRequest.serialize, - response_deserializer=page.ListPagesResponse.deserialize, - ) - return self._stubs['list_pages'] - - @property - def get_page(self) -> Callable[ - [page.GetPageRequest], - Awaitable[page.Page]]: - r"""Return a callable for the get page method over gRPC. - - Retrieves the specified page. - - Returns: - Callable[[~.GetPageRequest], - Awaitable[~.Page]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_page' not in self._stubs: - self._stubs['get_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Pages/GetPage', - request_serializer=page.GetPageRequest.serialize, - response_deserializer=page.Page.deserialize, - ) - return self._stubs['get_page'] - - @property - def create_page(self) -> Callable[ - [gcdc_page.CreatePageRequest], - Awaitable[gcdc_page.Page]]: - r"""Return a callable for the create page method over gRPC. - - Creates a page in the specified flow. - - Returns: - Callable[[~.CreatePageRequest], - Awaitable[~.Page]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_page' not in self._stubs: - self._stubs['create_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Pages/CreatePage', - request_serializer=gcdc_page.CreatePageRequest.serialize, - response_deserializer=gcdc_page.Page.deserialize, - ) - return self._stubs['create_page'] - - @property - def update_page(self) -> Callable[ - [gcdc_page.UpdatePageRequest], - Awaitable[gcdc_page.Page]]: - r"""Return a callable for the update page method over gRPC. - - Updates the specified page. - - Returns: - Callable[[~.UpdatePageRequest], - Awaitable[~.Page]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_page' not in self._stubs: - self._stubs['update_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Pages/UpdatePage', - request_serializer=gcdc_page.UpdatePageRequest.serialize, - response_deserializer=gcdc_page.Page.deserialize, - ) - return self._stubs['update_page'] - - @property - def delete_page(self) -> Callable[ - [page.DeletePageRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete page method over gRPC. - - Deletes the specified page. - - Returns: - Callable[[~.DeletePageRequest], - 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_page' not in self._stubs: - self._stubs['delete_page'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Pages/DeletePage', - request_serializer=page.DeletePageRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_page'] - - -__all__ = ( - 'PagesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py deleted file mode 100644 index 292d96e7..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__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 SecuritySettingsServiceClient -from .async_client import SecuritySettingsServiceAsyncClient - -__all__ = ( - 'SecuritySettingsServiceClient', - 'SecuritySettingsServiceAsyncClient', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py deleted file mode 100644 index b2dd0a48..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.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. -# -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.dialogflowcx_v3beta1.services.security_settings_service import pagers -from google.cloud.dialogflowcx_v3beta1.types import security_settings -from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport -from .client import SecuritySettingsServiceClient - - -class SecuritySettingsServiceAsyncClient: - """Service for managing security settings for Dialogflow.""" - - _client: SecuritySettingsServiceClient - - DEFAULT_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecuritySettingsServiceClient.DEFAULT_MTLS_ENDPOINT - - security_settings_path = staticmethod(SecuritySettingsServiceClient.security_settings_path) - parse_security_settings_path = staticmethod(SecuritySettingsServiceClient.parse_security_settings_path) - common_billing_account_path = staticmethod(SecuritySettingsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecuritySettingsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecuritySettingsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SecuritySettingsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SecuritySettingsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SecuritySettingsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SecuritySettingsServiceClient.common_project_path) - parse_common_project_path = staticmethod(SecuritySettingsServiceClient.parse_common_project_path) - common_location_path = staticmethod(SecuritySettingsServiceClient.common_location_path) - parse_common_location_path = staticmethod(SecuritySettingsServiceClient.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: - SecuritySettingsServiceAsyncClient: The constructed client. - """ - return SecuritySettingsServiceClient.from_service_account_info.__func__(SecuritySettingsServiceAsyncClient, 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: - SecuritySettingsServiceAsyncClient: The constructed client. - """ - return SecuritySettingsServiceClient.from_service_account_file.__func__(SecuritySettingsServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SecuritySettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SecuritySettingsServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SecuritySettingsServiceClient).get_transport_class, type(SecuritySettingsServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SecuritySettingsServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security settings service 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, ~.SecuritySettingsServiceTransport]): 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 = SecuritySettingsServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_security_settings(self, - request: gcdc_security_settings.CreateSecuritySettingsRequest = None, - *, - parent: str = None, - security_settings: gcdc_security_settings.SecuritySettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_security_settings.SecuritySettings: - r"""Create security settings in the specified location. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateSecuritySettingsRequest`): - The request object. The request message for - [SecuritySettings.CreateSecuritySettings][]. - parent (:class:`str`): - Required. The location to create an - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] - for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - security_settings (:class:`google.cloud.dialogflowcx_v3beta1.types.SecuritySettings`): - Required. The security settings to - create. - - This corresponds to the ``security_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, security_settings]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_security_settings.CreateSecuritySettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if security_settings is not None: - request.security_settings = security_settings - - # 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_security_settings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_security_settings(self, - request: security_settings.GetSecuritySettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> security_settings.SecuritySettings: - r"""Retrieves the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - The returned settings may be stale by up to 1 minute. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetSecuritySettingsRequest`): - The request object. The request message for - [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.GetSecuritySettings]. - name (:class:`str`): - Required. Resource name of the settings. Format: - ``projects//locations//securitySettings/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = security_settings.GetSecuritySettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_security_settings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_security_settings(self, - request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, - *, - security_settings: gcdc_security_settings.SecuritySettings = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_security_settings.SecuritySettings: - r"""Updates the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateSecuritySettingsRequest`): - The request object. The request message for - [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings]. - security_settings (:class:`google.cloud.dialogflowcx_v3beta1.types.SecuritySettings`): - Required. [SecuritySettings] object that contains values - for each of the fields to update. - - This corresponds to the ``security_settings`` 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.dialogflowcx_v3beta1.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_settings, 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 = gcdc_security_settings.UpdateSecuritySettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_settings is not None: - request.security_settings = security_settings - if update_mask is not None: - 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_security_settings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_settings.name", request.security_settings.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_security_settings(self, - request: security_settings.ListSecuritySettingsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSecuritySettingsAsyncPager: - r"""Returns the list of all security settings in the - specified location. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsRequest`): - The request object. The request message for - [SecuritySettings.ListSecuritySettings][]. - parent (:class:`str`): - Required. The location to list all security settings - 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.dialogflowcx_v3beta1.services.security_settings_service.pagers.ListSecuritySettingsAsyncPager: - The response message for - [SecuritySettings.ListSecuritySettings][]. - - 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 = security_settings.ListSecuritySettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_security_settings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListSecuritySettingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_security_settings(self, - request: security_settings.DeleteSecuritySettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteSecuritySettingsRequest`): - The request object. The request message for - [SecuritySettings.DeleteSecuritySettings][]. - name (:class:`str`): - Required. The name of the - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] - to delete. Format: - ``projects//locations//securitySettings/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = security_settings.DeleteSecuritySettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_security_settings, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SecuritySettingsServiceAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py deleted file mode 100644 index 502cfcc3..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/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 -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.dialogflowcx_v3beta1.services.security_settings_service import pagers -from google.cloud.dialogflowcx_v3beta1.types import security_settings -from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecuritySettingsServiceGrpcTransport -from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport - - -class SecuritySettingsServiceClientMeta(type): - """Metaclass for the SecuritySettingsService 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[SecuritySettingsServiceTransport]] - _transport_registry["grpc"] = SecuritySettingsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SecuritySettingsServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SecuritySettingsServiceTransport]: - """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 SecuritySettingsServiceClient(metaclass=SecuritySettingsServiceClientMeta): - """Service for managing security settings for Dialogflow.""" - - @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: - SecuritySettingsServiceClient: 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: - SecuritySettingsServiceClient: 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) -> SecuritySettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SecuritySettingsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def security_settings_path(project: str,location: str,security_settings: str,) -> str: - """Returns a fully-qualified security_settings string.""" - return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - - @staticmethod - def parse_security_settings_path(path: str) -> Dict[str,str]: - """Parses a security_settings path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def 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, SecuritySettingsServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security settings service 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, SecuritySettingsServiceTransport]): 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, SecuritySettingsServiceTransport): - # transport is a SecuritySettingsServiceTransport 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_security_settings(self, - request: gcdc_security_settings.CreateSecuritySettingsRequest = None, - *, - parent: str = None, - security_settings: gcdc_security_settings.SecuritySettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_security_settings.SecuritySettings: - r"""Create security settings in the specified location. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateSecuritySettingsRequest): - The request object. The request message for - [SecuritySettings.CreateSecuritySettings][]. - parent (str): - Required. The location to create an - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] - for. Format: - ``projects//locations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - security_settings (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings): - Required. The security settings to - create. - - This corresponds to the ``security_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, security_settings]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_security_settings.CreateSecuritySettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_security_settings.CreateSecuritySettingsRequest): - request = gcdc_security_settings.CreateSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if security_settings is not None: - request.security_settings = security_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_security_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_security_settings(self, - request: security_settings.GetSecuritySettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> security_settings.SecuritySettings: - r"""Retrieves the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - The returned settings may be stale by up to 1 minute. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetSecuritySettingsRequest): - The request object. The request message for - [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.GetSecuritySettings]. - name (str): - Required. Resource name of the settings. Format: - ``projects//locations//securitySettings/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 security_settings.GetSecuritySettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, security_settings.GetSecuritySettingsRequest): - request = security_settings.GetSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_security_settings] - - # Certain fields should be provided 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_security_settings(self, - request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, - *, - security_settings: gcdc_security_settings.SecuritySettings = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_security_settings.SecuritySettings: - r"""Updates the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateSecuritySettingsRequest): - The request object. The request message for - [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings]. - security_settings (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings): - Required. [SecuritySettings] object that contains values - for each of the fields to update. - - This corresponds to the ``security_settings`` 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.dialogflowcx_v3beta1.types.SecuritySettings: - Represents the settings related to - security issues, such as data redaction - and data retention. It may take hours - for updates on the settings to propagate - to all the related components and take - effect. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_settings, 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 gcdc_security_settings.UpdateSecuritySettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_security_settings.UpdateSecuritySettingsRequest): - request = gcdc_security_settings.UpdateSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_settings is not None: - request.security_settings = security_settings - if update_mask is not None: - 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_security_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_settings.name", request.security_settings.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_security_settings(self, - request: security_settings.ListSecuritySettingsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSecuritySettingsPager: - r"""Returns the list of all security settings in the - specified location. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsRequest): - The request object. The request message for - [SecuritySettings.ListSecuritySettings][]. - parent (str): - Required. The location to list all security settings - 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.dialogflowcx_v3beta1.services.security_settings_service.pagers.ListSecuritySettingsPager: - The response message for - [SecuritySettings.ListSecuritySettings][]. - - 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 security_settings.ListSecuritySettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, security_settings.ListSecuritySettingsRequest): - request = security_settings.ListSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_security_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListSecuritySettingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_security_settings(self, - request: security_settings.DeleteSecuritySettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.DeleteSecuritySettingsRequest): - The request object. The request message for - [SecuritySettings.DeleteSecuritySettings][]. - name (str): - Required. The name of the - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] - to delete. Format: - ``projects//locations//securitySettings/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 security_settings.DeleteSecuritySettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, security_settings.DeleteSecuritySettingsRequest): - request = security_settings.DeleteSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_security_settings] - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SecuritySettingsServiceClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py deleted file mode 100644 index 040993a7..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/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.dialogflowcx_v3beta1.types import security_settings - - -class ListSecuritySettingsPager: - """A pager for iterating through ``list_security_settings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``security_settings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSecuritySettings`` requests and continue to iterate - through the ``security_settings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse` - 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[..., security_settings.ListSecuritySettingsResponse], - request: security_settings.ListSecuritySettingsRequest, - response: security_settings.ListSecuritySettingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse): - 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 = security_settings.ListSecuritySettingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[security_settings.ListSecuritySettingsResponse]: - 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[security_settings.SecuritySettings]: - for page in self.pages: - yield from page.security_settings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSecuritySettingsAsyncPager: - """A pager for iterating through ``list_security_settings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``security_settings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSecuritySettings`` requests and continue to iterate - through the ``security_settings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse` - 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[security_settings.ListSecuritySettingsResponse]], - request: security_settings.ListSecuritySettingsRequest, - response: security_settings.ListSecuritySettingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListSecuritySettingsResponse): - 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 = security_settings.ListSecuritySettingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[security_settings.ListSecuritySettingsResponse]: - 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[security_settings.SecuritySettings]: - async def async_generator(): - async for page in self.pages: - for response in page.security_settings: - 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py deleted file mode 100644 index 116b7680..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/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 SecuritySettingsServiceTransport -from .grpc import SecuritySettingsServiceGrpcTransport -from .grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecuritySettingsServiceTransport]] -_transport_registry['grpc'] = SecuritySettingsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SecuritySettingsServiceGrpcAsyncIOTransport - -__all__ = ( - 'SecuritySettingsServiceTransport', - 'SecuritySettingsServiceGrpcTransport', - 'SecuritySettingsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/base.py deleted file mode 100644 index 552d4b3a..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/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.dialogflowcx_v3beta1.types import security_settings -from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflowcx', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class SecuritySettingsServiceTransport(abc.ABC): - """Abstract transport class for SecuritySettingsService.""" - - 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_security_settings: gapic_v1.method.wrap_method( - self.create_security_settings, - default_timeout=None, - client_info=client_info, - ), - self.get_security_settings: gapic_v1.method.wrap_method( - self.get_security_settings, - default_timeout=None, - client_info=client_info, - ), - self.update_security_settings: gapic_v1.method.wrap_method( - self.update_security_settings, - default_timeout=None, - client_info=client_info, - ), - self.list_security_settings: gapic_v1.method.wrap_method( - self.list_security_settings, - default_timeout=None, - client_info=client_info, - ), - self.delete_security_settings: gapic_v1.method.wrap_method( - self.delete_security_settings, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def create_security_settings(self) -> Callable[ - [gcdc_security_settings.CreateSecuritySettingsRequest], - Union[ - gcdc_security_settings.SecuritySettings, - Awaitable[gcdc_security_settings.SecuritySettings] - ]]: - raise NotImplementedError() - - @property - def get_security_settings(self) -> Callable[ - [security_settings.GetSecuritySettingsRequest], - Union[ - security_settings.SecuritySettings, - Awaitable[security_settings.SecuritySettings] - ]]: - raise NotImplementedError() - - @property - def update_security_settings(self) -> Callable[ - [gcdc_security_settings.UpdateSecuritySettingsRequest], - Union[ - gcdc_security_settings.SecuritySettings, - Awaitable[gcdc_security_settings.SecuritySettings] - ]]: - raise NotImplementedError() - - @property - def list_security_settings(self) -> Callable[ - [security_settings.ListSecuritySettingsRequest], - Union[ - security_settings.ListSecuritySettingsResponse, - Awaitable[security_settings.ListSecuritySettingsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_security_settings(self) -> Callable[ - [security_settings.DeleteSecuritySettingsRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'SecuritySettingsServiceTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py deleted file mode 100644 index 59688392..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py +++ /dev/null @@ -1,359 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflowcx_v3beta1.types import security_settings -from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings -from google.protobuf import empty_pb2 # type: ignore -from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO - - -class SecuritySettingsServiceGrpcTransport(SecuritySettingsServiceTransport): - """gRPC backend transport for SecuritySettingsService. - - Service for managing security settings for Dialogflow. - - 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_security_settings(self) -> Callable[ - [gcdc_security_settings.CreateSecuritySettingsRequest], - gcdc_security_settings.SecuritySettings]: - r"""Return a callable for the create security settings method over gRPC. - - Create security settings in the specified location. - - Returns: - Callable[[~.CreateSecuritySettingsRequest], - ~.SecuritySettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_settings' not in self._stubs: - self._stubs['create_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/CreateSecuritySettings', - request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, - response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, - ) - return self._stubs['create_security_settings'] - - @property - def get_security_settings(self) -> Callable[ - [security_settings.GetSecuritySettingsRequest], - security_settings.SecuritySettings]: - r"""Return a callable for the get security settings method over gRPC. - - Retrieves the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - The returned settings may be stale by up to 1 minute. - - Returns: - Callable[[~.GetSecuritySettingsRequest], - ~.SecuritySettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_security_settings' not in self._stubs: - self._stubs['get_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/GetSecuritySettings', - request_serializer=security_settings.GetSecuritySettingsRequest.serialize, - response_deserializer=security_settings.SecuritySettings.deserialize, - ) - return self._stubs['get_security_settings'] - - @property - def update_security_settings(self) -> Callable[ - [gcdc_security_settings.UpdateSecuritySettingsRequest], - gcdc_security_settings.SecuritySettings]: - r"""Return a callable for the update security settings method over gRPC. - - Updates the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - - Returns: - Callable[[~.UpdateSecuritySettingsRequest], - ~.SecuritySettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_settings' not in self._stubs: - self._stubs['update_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/UpdateSecuritySettings', - request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, - response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, - ) - return self._stubs['update_security_settings'] - - @property - def list_security_settings(self) -> Callable[ - [security_settings.ListSecuritySettingsRequest], - security_settings.ListSecuritySettingsResponse]: - r"""Return a callable for the list security settings method over gRPC. - - Returns the list of all security settings in the - specified location. - - Returns: - Callable[[~.ListSecuritySettingsRequest], - ~.ListSecuritySettingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_security_settings' not in self._stubs: - self._stubs['list_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/ListSecuritySettings', - request_serializer=security_settings.ListSecuritySettingsRequest.serialize, - response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, - ) - return self._stubs['list_security_settings'] - - @property - def delete_security_settings(self) -> Callable[ - [security_settings.DeleteSecuritySettingsRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete security settings method over gRPC. - - Deletes the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - - Returns: - Callable[[~.DeleteSecuritySettingsRequest], - ~.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_security_settings' not in self._stubs: - self._stubs['delete_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/DeleteSecuritySettings', - request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_security_settings'] - - -__all__ = ( - 'SecuritySettingsServiceGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py deleted file mode 100644 index aa3458ca..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,363 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import security_settings -from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings -from google.protobuf import empty_pb2 # type: ignore -from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SecuritySettingsServiceGrpcTransport - - -class SecuritySettingsServiceGrpcAsyncIOTransport(SecuritySettingsServiceTransport): - """gRPC AsyncIO backend transport for SecuritySettingsService. - - Service for managing security settings for Dialogflow. - - 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_security_settings(self) -> Callable[ - [gcdc_security_settings.CreateSecuritySettingsRequest], - Awaitable[gcdc_security_settings.SecuritySettings]]: - r"""Return a callable for the create security settings method over gRPC. - - Create security settings in the specified location. - - Returns: - Callable[[~.CreateSecuritySettingsRequest], - Awaitable[~.SecuritySettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_settings' not in self._stubs: - self._stubs['create_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/CreateSecuritySettings', - request_serializer=gcdc_security_settings.CreateSecuritySettingsRequest.serialize, - response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, - ) - return self._stubs['create_security_settings'] - - @property - def get_security_settings(self) -> Callable[ - [security_settings.GetSecuritySettingsRequest], - Awaitable[security_settings.SecuritySettings]]: - r"""Return a callable for the get security settings method over gRPC. - - Retrieves the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - The returned settings may be stale by up to 1 minute. - - Returns: - Callable[[~.GetSecuritySettingsRequest], - Awaitable[~.SecuritySettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_security_settings' not in self._stubs: - self._stubs['get_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/GetSecuritySettings', - request_serializer=security_settings.GetSecuritySettingsRequest.serialize, - response_deserializer=security_settings.SecuritySettings.deserialize, - ) - return self._stubs['get_security_settings'] - - @property - def update_security_settings(self) -> Callable[ - [gcdc_security_settings.UpdateSecuritySettingsRequest], - Awaitable[gcdc_security_settings.SecuritySettings]]: - r"""Return a callable for the update security settings method over gRPC. - - Updates the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - - Returns: - Callable[[~.UpdateSecuritySettingsRequest], - Awaitable[~.SecuritySettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_settings' not in self._stubs: - self._stubs['update_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/UpdateSecuritySettings', - request_serializer=gcdc_security_settings.UpdateSecuritySettingsRequest.serialize, - response_deserializer=gcdc_security_settings.SecuritySettings.deserialize, - ) - return self._stubs['update_security_settings'] - - @property - def list_security_settings(self) -> Callable[ - [security_settings.ListSecuritySettingsRequest], - Awaitable[security_settings.ListSecuritySettingsResponse]]: - r"""Return a callable for the list security settings method over gRPC. - - Returns the list of all security settings in the - specified location. - - Returns: - Callable[[~.ListSecuritySettingsRequest], - Awaitable[~.ListSecuritySettingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_security_settings' not in self._stubs: - self._stubs['list_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/ListSecuritySettings', - request_serializer=security_settings.ListSecuritySettingsRequest.serialize, - response_deserializer=security_settings.ListSecuritySettingsResponse.deserialize, - ) - return self._stubs['list_security_settings'] - - @property - def delete_security_settings(self) -> Callable[ - [security_settings.DeleteSecuritySettingsRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete security settings method over gRPC. - - Deletes the specified - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings]. - - Returns: - Callable[[~.DeleteSecuritySettingsRequest], - 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_security_settings' not in self._stubs: - self._stubs['delete_security_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/DeleteSecuritySettings', - request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_security_settings'] - - -__all__ = ( - 'SecuritySettingsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py deleted file mode 100644 index fb6678b1..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py deleted file mode 100644 index c410c4d4..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/async_client.py +++ /dev/null @@ -1,635 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.session_entity_types import pagers -from google.cloud.dialogflowcx_v3beta1.types import entity_type -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_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.cx.v3beta1.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. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest`): - The request object. The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.ListSessionEntityTypes]. - parent (:class:`str`): - Required. The session to list all session entity types - from. Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager: - The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.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. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetSessionEntityTypeRequest`): - The request object. The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.GetSessionEntityType]. - name (:class:`str`): - Required. The name of the session entity type. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3beta1.EntityType] - at the user session level (we refer to the entity - types defined at the agent level as "custom entity - types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not 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: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, - *, - parent: str = None, - session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_session_entity_type.SessionEntityType: - r"""Creates a session entity type. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateSessionEntityTypeRequest`): - The request object. The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.CreateSessionEntityType]. - parent (:class:`str`): - Required. The session to create a session entity type - for. Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - 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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3beta1.EntityType] - at the user session level (we refer to the entity - types defined at the agent level as "custom entity - types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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, 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 = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if session_entity_type is not None: - 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: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, - *, - session_entity_type: gcdc_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]] = (), - ) -> gcdc_session_entity_type.SessionEntityType: - r"""Updates the specified session entity type. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateSessionEntityTypeRequest`): - The request object. The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.UpdateSessionEntityType]. - session_entity_type (:class:`google.cloud.dialogflowcx_v3beta1.types.SessionEntityType`): - Required. The session entity type to update. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - 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`): - 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.dialogflowcx_v3beta1.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3beta1.EntityType] - at the user session level (we refer to the entity - types defined at the agent level as "custom entity - types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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([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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if session_entity_type is not None: - request.session_entity_type = session_entity_type - if update_mask is not None: - 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. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteSessionEntityTypeRequest`): - The request object. The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.DeleteSessionEntityType]. - name (:class:`str`): - Required. The name of the session entity type to delete. - Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SessionEntityTypesAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py deleted file mode 100644 index 8445e990..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py +++ /dev/null @@ -1,822 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.session_entity_types import pagers -from google.cloud.dialogflowcx_v3beta1.types import entity_type -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_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.cx.v3beta1.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,location: str,agent: str,session: str,entity_type: str,) -> str: - """Returns a fully-qualified session_entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, 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.+?)/locations/(?P.+?)/agents/(?P.+?)/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. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest): - The request object. The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.ListSessionEntityTypes]. - parent (str): - Required. The session to list all session entity types - from. Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.session_entity_types.pagers.ListSessionEntityTypesPager: - The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.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. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.GetSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.GetSessionEntityType]. - name (str): - Required. The name of the session entity type. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3beta1.EntityType] - at the user session level (we refer to the entity - types defined at the agent level as "custom entity - types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is 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: gcdc_session_entity_type.CreateSessionEntityTypeRequest = None, - *, - parent: str = None, - session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_session_entity_type.SessionEntityType: - r"""Creates a session entity type. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.CreateSessionEntityType]. - parent (str): - Required. The session to create a session entity type - for. Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - session_entity_type (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3beta1.EntityType] - at the user session level (we refer to the entity - types defined at the agent level as "custom entity - types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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, 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 gcdc_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, gcdc_session_entity_type.CreateSessionEntityTypeRequest): - request = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if session_entity_type is not None: - 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: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, - *, - session_entity_type: gcdc_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]] = (), - ) -> gcdc_session_entity_type.SessionEntityType: - r"""Updates the specified session entity type. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.UpdateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.UpdateSessionEntityType]. - session_entity_type (google.cloud.dialogflowcx_v3beta1.types.SessionEntityType): - Required. The session entity type to update. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - 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): - 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.dialogflowcx_v3beta1.types.SessionEntityType: - Session entity types are referred to as **User** entity types and are - entities that are built for an individual user such - as favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session - level to extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3beta1.EntityType] - at the user session level (we refer to the entity - types defined at the agent level as "custom entity - types"). - - Note: session entity types apply to all queries, - regardless of the language. - - For more information about entity types, see the - [Dialogflow - documentation](\ 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([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 gcdc_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, gcdc_session_entity_type.UpdateSessionEntityTypeRequest): - request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if session_entity_type is not None: - request.session_entity_type = session_entity_type - if update_mask is not None: - 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. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.DeleteSessionEntityTypeRequest): - The request object. The request message for - [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.DeleteSessionEntityType]. - name (str): - Required. The name of the session entity type to delete. - Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume - default 'draft' environment. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SessionEntityTypesClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py deleted file mode 100644 index c51702a3..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListSessionEntityTypesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py deleted file mode 100644 index fee52672..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/base.py deleted file mode 100644 index 7aa63002..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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.dialogflowcx_v3beta1.types import session_entity_type -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_session_entity_type -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflowcx', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -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[ - [gcdc_session_entity_type.CreateSessionEntityTypeRequest], - Union[ - gcdc_session_entity_type.SessionEntityType, - Awaitable[gcdc_session_entity_type.SessionEntityType] - ]]: - raise NotImplementedError() - - @property - def update_session_entity_type(self) -> Callable[ - [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], - Union[ - gcdc_session_entity_type.SessionEntityType, - Awaitable[gcdc_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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py deleted file mode 100644 index c2eedab0..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/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.dialogflowcx_v3beta1.types import session_entity_type -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_session_entity_type -from google.protobuf import empty_pb2 # type: ignore -from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO - - -class SessionEntityTypesGrpcTransport(SessionEntityTypesTransport): - """gRPC backend transport for SessionEntityTypes. - - Service for managing - [SessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.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. - - 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.cx.v3beta1.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. - - 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.cx.v3beta1.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[ - [gcdc_session_entity_type.CreateSessionEntityTypeRequest], - gcdc_session_entity_type.SessionEntityType]: - r"""Return a callable for the create session entity type method over gRPC. - - Creates a session entity type. - - 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.cx.v3beta1.SessionEntityTypes/CreateSessionEntityType', - request_serializer=gcdc_session_entity_type.CreateSessionEntityTypeRequest.serialize, - response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['create_session_entity_type'] - - @property - def update_session_entity_type(self) -> Callable[ - [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], - gcdc_session_entity_type.SessionEntityType]: - r"""Return a callable for the update session entity type method over gRPC. - - Updates the specified session entity type. - - 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.cx.v3beta1.SessionEntityTypes/UpdateSessionEntityType', - request_serializer=gcdc_session_entity_type.UpdateSessionEntityTypeRequest.serialize, - response_deserializer=gcdc_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. - - 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.cx.v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc_asyncio.py deleted file mode 100644 index 357754dd..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/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.dialogflowcx_v3beta1.types import session_entity_type -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_session_entity_type -from google.protobuf import empty_pb2 # 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.cx.v3beta1.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. - - 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.cx.v3beta1.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. - - 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.cx.v3beta1.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[ - [gcdc_session_entity_type.CreateSessionEntityTypeRequest], - Awaitable[gcdc_session_entity_type.SessionEntityType]]: - r"""Return a callable for the create session entity type method over gRPC. - - Creates a session entity type. - - 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.cx.v3beta1.SessionEntityTypes/CreateSessionEntityType', - request_serializer=gcdc_session_entity_type.CreateSessionEntityTypeRequest.serialize, - response_deserializer=gcdc_session_entity_type.SessionEntityType.deserialize, - ) - return self._stubs['create_session_entity_type'] - - @property - def update_session_entity_type(self) -> Callable[ - [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], - Awaitable[gcdc_session_entity_type.SessionEntityType]]: - r"""Return a callable for the update session entity type method over gRPC. - - Updates the specified session entity type. - - 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.cx.v3beta1.SessionEntityTypes/UpdateSessionEntityType', - request_serializer=gcdc_session_entity_type.UpdateSessionEntityTypeRequest.serialize, - response_deserializer=gcdc_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. - - 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.cx.v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py deleted file mode 100644 index 92490cc5..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py deleted file mode 100644 index e6fcf7ba..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py +++ /dev/null @@ -1,460 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.types import audio_config -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import session -from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport -from .client import SessionsClient - - -class SessionsAsyncClient: - """A session represents an interaction with a user. You retrieve user - input and pass it to the - [DetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.DetectIntent] - method to determine user intent and respond. - """ - - _client: SessionsClient - - DEFAULT_ENDPOINT = SessionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SessionsClient.DEFAULT_MTLS_ENDPOINT - - entity_type_path = staticmethod(SessionsClient.entity_type_path) - parse_entity_type_path = staticmethod(SessionsClient.parse_entity_type_path) - flow_path = staticmethod(SessionsClient.flow_path) - parse_flow_path = staticmethod(SessionsClient.parse_flow_path) - intent_path = staticmethod(SessionsClient.intent_path) - parse_intent_path = staticmethod(SessionsClient.parse_intent_path) - page_path = staticmethod(SessionsClient.page_path) - parse_page_path = staticmethod(SessionsClient.parse_page_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) - transition_route_group_path = staticmethod(SessionsClient.transition_route_group_path) - parse_transition_route_group_path = staticmethod(SessionsClient.parse_transition_route_group_path) - webhook_path = staticmethod(SessionsClient.webhook_path) - parse_webhook_path = staticmethod(SessionsClient.parse_webhook_path) - common_billing_account_path = staticmethod(SessionsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SessionsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SessionsClient.common_folder_path) - parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) - common_organization_path = staticmethod(SessionsClient.common_organization_path) - parse_common_organization_path = staticmethod(SessionsClient.parse_common_organization_path) - common_project_path = staticmethod(SessionsClient.common_project_path) - parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) - common_location_path = staticmethod(SessionsClient.common_location_path) - parse_common_location_path = staticmethod(SessionsClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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: session.DetectIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> 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 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.dialogflowcx_v3beta1.types.DetectIntentRequest`): - The request object. The request to detect user's intent. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.DetectIntentResponse: - The message returned from the - DetectIntent method. - - """ - # Create or coerce a protobuf request object. - request = session.DetectIntentRequest(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.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.dialogflowcx_v3beta1.types.StreamingDetectIntentRequest`]): - The request object AsyncIterator. The top-level message sent by the - client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.StreamingDetectIntent] - method. - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.output_audio_config]. - 2. If - [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio.config][google.cloud.dialogflow.cx.v3beta1.AudioInput.config], - all subsequent messages must contain - [query_input.audio.audio][google.cloud.dialogflow.cx.v3beta1.AudioInput.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.cx.v3beta1.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.dialogflowcx_v3beta1.types.StreamingDetectIntentResponse]: - The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. If enable_partial_response is true, the following - N messages (currently 1 <= N <= 4) contain - detect_intent_response. The first (N-1) - detect_intent_responses will have response_type - set to PARTIAL. The last detect_intent_response - has response_type set to FINAL. If response_type - is false, response stream only contains the final - detect_intent_response. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_detect_intent, - default_timeout=220.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def match_intent(self, - request: session.MatchIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session.MatchIntentResponse: - r"""Returns preliminary intent match results, doesn't - change the session status. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest`): - The request object. Request of [MatchIntent][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.MatchIntentResponse: - Response of [MatchIntent][]. - """ - # Create or coerce a protobuf request object. - request = session.MatchIntentRequest(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.match_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(( - ("session", request.session), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def fulfill_intent(self, - request: session.FulfillIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session.FulfillIntentResponse: - r"""Fulfills a matched intent returned by - [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent]. - Must be called after - [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent], - with input from - [MatchIntentResponse][google.cloud.dialogflow.cx.v3beta1.MatchIntentResponse]. - Otherwise, the behavior is undefined. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.FulfillIntentRequest`): - The request object. Request of [FulfillIntent][] - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.FulfillIntentResponse: - Response of [FulfillIntent][] - """ - # Create or coerce a protobuf request object. - request = session.FulfillIntentRequest(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.fulfill_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(( - ("match_intent_request.session", request.match_intent_request.session), - )), - ) - - # 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SessionsAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py deleted file mode 100644 index 197afabe..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/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 -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.dialogflowcx_v3beta1.types import audio_config -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import session -from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SessionsGrpcTransport -from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport - - -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 session represents an interaction with a user. You retrieve user - input and pass it to the - [DetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.DetectIntent] - method to determine user intent and respond. - """ - - @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 entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: - """Returns a fully-qualified page string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - - @staticmethod - def parse_page_path(path: str) -> Dict[str,str]: - """Parses a page path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def session_path(project: str,location: str,agent: str,session: str,) -> str: - """Returns a fully-qualified session string.""" - return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format(project=project, location=location, agent=agent, session=session, ) - - @staticmethod - def parse_session_path(path: str) -> Dict[str,str]: - """Parses a session path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def session_entity_type_path(project: str,location: str,agent: str,session: str,entity_type: str,) -> str: - """Returns a fully-qualified session_entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, 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.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: - """Returns a fully-qualified transition_route_group string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - - @staticmethod - def parse_transition_route_group_path(path: str) -> Dict[str,str]: - """Parses a transition_route_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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: session.DetectIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> 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 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.dialogflowcx_v3beta1.types.DetectIntentRequest): - The request object. The request to detect user's intent. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.DetectIntentResponse: - The message returned from the - DetectIntent method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a session.DetectIntentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, session.DetectIntentRequest): - request = session.DetectIntentRequest(request) - - # 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.dialogflowcx_v3beta1.types.StreamingDetectIntentRequest]): - The request object iterator. The top-level message sent by the - client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.StreamingDetectIntent] - method. - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it - should also contain - [output_audio_config][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.output_audio_config]. - 2. If - [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio.config][google.cloud.dialogflow.cx.v3beta1.AudioInput.config], - all subsequent messages must contain - [query_input.audio.audio][google.cloud.dialogflow.cx.v3beta1.AudioInput.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.cx.v3beta1.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.dialogflowcx_v3beta1.types.StreamingDetectIntentResponse]: - The top-level message returned from the - StreamingDetectIntent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. If enable_partial_response is true, the following - N messages (currently 1 <= N <= 4) contain - detect_intent_response. The first (N-1) - detect_intent_responses will have response_type - set to PARTIAL. The last detect_intent_response - has response_type set to FINAL. If response_type - is false, response stream only contains the final - detect_intent_response. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.streaming_detect_intent] - - # Send the request. - response = rpc( - requests, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def match_intent(self, - request: session.MatchIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session.MatchIntentResponse: - r"""Returns preliminary intent match results, doesn't - change the session status. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest): - The request object. Request of [MatchIntent][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.MatchIntentResponse: - Response of [MatchIntent][]. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a session.MatchIntentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, session.MatchIntentRequest): - request = session.MatchIntentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.match_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 fulfill_intent(self, - request: session.FulfillIntentRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> session.FulfillIntentResponse: - r"""Fulfills a matched intent returned by - [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent]. - Must be called after - [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent], - with input from - [MatchIntentResponse][google.cloud.dialogflow.cx.v3beta1.MatchIntentResponse]. - Otherwise, the behavior is undefined. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.FulfillIntentRequest): - The request object. Request of [FulfillIntent][] - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.FulfillIntentResponse: - Response of [FulfillIntent][] - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a session.FulfillIntentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, session.FulfillIntentRequest): - request = session.FulfillIntentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.fulfill_intent] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("match_intent_request.session", request.match_intent_request.session), - )), - ) - - # 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SessionsClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py deleted file mode 100644 index fde19f61..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py deleted file mode 100644 index 14df3697..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py +++ /dev/null @@ -1,231 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import session - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflowcx', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -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, - ), - self.match_intent: gapic_v1.method.wrap_method( - self.match_intent, - default_timeout=None, - client_info=client_info, - ), - self.fulfill_intent: gapic_v1.method.wrap_method( - self.fulfill_intent, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def detect_intent(self) -> Callable[ - [session.DetectIntentRequest], - Union[ - session.DetectIntentResponse, - Awaitable[session.DetectIntentResponse] - ]]: - raise NotImplementedError() - - @property - def streaming_detect_intent(self) -> Callable[ - [session.StreamingDetectIntentRequest], - Union[ - session.StreamingDetectIntentResponse, - Awaitable[session.StreamingDetectIntentResponse] - ]]: - raise NotImplementedError() - - @property - def match_intent(self) -> Callable[ - [session.MatchIntentRequest], - Union[ - session.MatchIntentResponse, - Awaitable[session.MatchIntentResponse] - ]]: - raise NotImplementedError() - - @property - def fulfill_intent(self) -> Callable[ - [session.FulfillIntentRequest], - Union[ - session.FulfillIntentResponse, - Awaitable[session.FulfillIntentResponse] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'SessionsTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py deleted file mode 100644 index 43f88d66..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.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 warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflowcx_v3beta1.types import session -from .base import SessionsTransport, DEFAULT_CLIENT_INFO - - -class SessionsGrpcTransport(SessionsTransport): - """gRPC backend transport for Sessions. - - A session represents an interaction with a user. You retrieve user - input and pass it to the - [DetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.DetectIntent] - method to determine user intent and respond. - - 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[ - [session.DetectIntentRequest], - 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 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.cx.v3beta1.Sessions/DetectIntent', - request_serializer=session.DetectIntentRequest.serialize, - response_deserializer=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.cx.v3beta1.Sessions/StreamingDetectIntent', - request_serializer=session.StreamingDetectIntentRequest.serialize, - response_deserializer=session.StreamingDetectIntentResponse.deserialize, - ) - return self._stubs['streaming_detect_intent'] - - @property - def match_intent(self) -> Callable[ - [session.MatchIntentRequest], - session.MatchIntentResponse]: - r"""Return a callable for the match intent method over gRPC. - - Returns preliminary intent match results, doesn't - change the session status. - - Returns: - Callable[[~.MatchIntentRequest], - ~.MatchIntentResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'match_intent' not in self._stubs: - self._stubs['match_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Sessions/MatchIntent', - request_serializer=session.MatchIntentRequest.serialize, - response_deserializer=session.MatchIntentResponse.deserialize, - ) - return self._stubs['match_intent'] - - @property - def fulfill_intent(self) -> Callable[ - [session.FulfillIntentRequest], - session.FulfillIntentResponse]: - r"""Return a callable for the fulfill intent method over gRPC. - - Fulfills a matched intent returned by - [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent]. - Must be called after - [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent], - with input from - [MatchIntentResponse][google.cloud.dialogflow.cx.v3beta1.MatchIntentResponse]. - Otherwise, the behavior is undefined. - - Returns: - Callable[[~.FulfillIntentRequest], - ~.FulfillIntentResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fulfill_intent' not in self._stubs: - self._stubs['fulfill_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Sessions/FulfillIntent', - request_serializer=session.FulfillIntentRequest.serialize, - response_deserializer=session.FulfillIntentResponse.deserialize, - ) - return self._stubs['fulfill_intent'] - - -__all__ = ( - 'SessionsGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py deleted file mode 100644 index 9e0d3c1a..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py +++ /dev/null @@ -1,354 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import session -from .base import SessionsTransport, DEFAULT_CLIENT_INFO -from .grpc import SessionsGrpcTransport - - -class SessionsGrpcAsyncIOTransport(SessionsTransport): - """gRPC AsyncIO backend transport for Sessions. - - A session represents an interaction with a user. You retrieve user - input and pass it to the - [DetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.DetectIntent] - method to determine user intent and respond. - - 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[ - [session.DetectIntentRequest], - Awaitable[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 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.cx.v3beta1.Sessions/DetectIntent', - request_serializer=session.DetectIntentRequest.serialize, - response_deserializer=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.cx.v3beta1.Sessions/StreamingDetectIntent', - request_serializer=session.StreamingDetectIntentRequest.serialize, - response_deserializer=session.StreamingDetectIntentResponse.deserialize, - ) - return self._stubs['streaming_detect_intent'] - - @property - def match_intent(self) -> Callable[ - [session.MatchIntentRequest], - Awaitable[session.MatchIntentResponse]]: - r"""Return a callable for the match intent method over gRPC. - - Returns preliminary intent match results, doesn't - change the session status. - - Returns: - Callable[[~.MatchIntentRequest], - Awaitable[~.MatchIntentResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'match_intent' not in self._stubs: - self._stubs['match_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Sessions/MatchIntent', - request_serializer=session.MatchIntentRequest.serialize, - response_deserializer=session.MatchIntentResponse.deserialize, - ) - return self._stubs['match_intent'] - - @property - def fulfill_intent(self) -> Callable[ - [session.FulfillIntentRequest], - Awaitable[session.FulfillIntentResponse]]: - r"""Return a callable for the fulfill intent method over gRPC. - - Fulfills a matched intent returned by - [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent]. - Must be called after - [MatchIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.MatchIntent], - with input from - [MatchIntentResponse][google.cloud.dialogflow.cx.v3beta1.MatchIntentResponse]. - Otherwise, the behavior is undefined. - - Returns: - Callable[[~.FulfillIntentRequest], - Awaitable[~.FulfillIntentResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fulfill_intent' not in self._stubs: - self._stubs['fulfill_intent'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Sessions/FulfillIntent', - request_serializer=session.FulfillIntentRequest.serialize, - response_deserializer=session.FulfillIntentResponse.deserialize, - ) - return self._stubs['fulfill_intent'] - - -__all__ = ( - 'SessionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py deleted file mode 100644 index 938c210f..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/__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 TestCasesClient -from .async_client import TestCasesAsyncClient - -__all__ = ( - 'TestCasesClient', - 'TestCasesAsyncClient', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py deleted file mode 100644 index 4f110481..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py +++ /dev/null @@ -1,1073 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.test_cases import pagers -from google.cloud.dialogflowcx_v3beta1.types import test_case -from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport -from .client import TestCasesClient - - -class TestCasesAsyncClient: - """Service for managing [Test - Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and [Test Case - Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult]. - """ - - _client: TestCasesClient - - DEFAULT_ENDPOINT = TestCasesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TestCasesClient.DEFAULT_MTLS_ENDPOINT - - agent_path = staticmethod(TestCasesClient.agent_path) - parse_agent_path = staticmethod(TestCasesClient.parse_agent_path) - entity_type_path = staticmethod(TestCasesClient.entity_type_path) - parse_entity_type_path = staticmethod(TestCasesClient.parse_entity_type_path) - environment_path = staticmethod(TestCasesClient.environment_path) - parse_environment_path = staticmethod(TestCasesClient.parse_environment_path) - flow_path = staticmethod(TestCasesClient.flow_path) - parse_flow_path = staticmethod(TestCasesClient.parse_flow_path) - intent_path = staticmethod(TestCasesClient.intent_path) - parse_intent_path = staticmethod(TestCasesClient.parse_intent_path) - page_path = staticmethod(TestCasesClient.page_path) - parse_page_path = staticmethod(TestCasesClient.parse_page_path) - test_case_path = staticmethod(TestCasesClient.test_case_path) - parse_test_case_path = staticmethod(TestCasesClient.parse_test_case_path) - test_case_result_path = staticmethod(TestCasesClient.test_case_result_path) - parse_test_case_result_path = staticmethod(TestCasesClient.parse_test_case_result_path) - transition_route_group_path = staticmethod(TestCasesClient.transition_route_group_path) - parse_transition_route_group_path = staticmethod(TestCasesClient.parse_transition_route_group_path) - webhook_path = staticmethod(TestCasesClient.webhook_path) - parse_webhook_path = staticmethod(TestCasesClient.parse_webhook_path) - common_billing_account_path = staticmethod(TestCasesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TestCasesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TestCasesClient.common_folder_path) - parse_common_folder_path = staticmethod(TestCasesClient.parse_common_folder_path) - common_organization_path = staticmethod(TestCasesClient.common_organization_path) - parse_common_organization_path = staticmethod(TestCasesClient.parse_common_organization_path) - common_project_path = staticmethod(TestCasesClient.common_project_path) - parse_common_project_path = staticmethod(TestCasesClient.parse_common_project_path) - common_location_path = staticmethod(TestCasesClient.common_location_path) - parse_common_location_path = staticmethod(TestCasesClient.parse_common_location_path) - - @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: - TestCasesAsyncClient: The constructed client. - """ - return TestCasesClient.from_service_account_info.__func__(TestCasesAsyncClient, 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: - TestCasesAsyncClient: The constructed client. - """ - return TestCasesClient.from_service_account_file.__func__(TestCasesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> TestCasesTransport: - """Returns the transport used by the client instance. - - Returns: - TestCasesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(TestCasesClient).get_transport_class, type(TestCasesClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, TestCasesTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the test cases 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, ~.TestCasesTransport]): 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 = TestCasesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_test_cases(self, - request: test_case.ListTestCasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTestCasesAsyncPager: - r"""Fetches a list of test cases for a given agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest`): - The request object. The request message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. - parent (:class:`str`): - Required. The agent to list all pages for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers.ListTestCasesAsyncPager: - The response message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. - - 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 = test_case.ListTestCasesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_test_cases, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListTestCasesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_delete_test_cases(self, - request: test_case.BatchDeleteTestCasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Batch deletes test cases. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.BatchDeleteTestCasesRequest`): - The request object. The request message for - [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchDeleteTestCases]. - parent (:class:`str`): - Required. The agent to delete test cases from. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = test_case.BatchDeleteTestCasesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_test_cases, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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 get_test_case(self, - request: test_case.GetTestCaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.TestCase: - r"""Gets a test case. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetTestCaseRequest`): - The request object. The request message for - [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCase]. - name (:class:`str`): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = test_case.GetTestCaseRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_test_case, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_test_case(self, - request: gcdc_test_case.CreateTestCaseRequest = None, - *, - parent: str = None, - test_case: gcdc_test_case.TestCase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_test_case.TestCase: - r"""Creates a test case for the given agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateTestCaseRequest`): - The request object. The request message for - [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.CreateTestCase]. - parent (:class:`str`): - Required. The agent to create the test case for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - test_case (:class:`google.cloud.dialogflowcx_v3beta1.types.TestCase`): - Required. The test case to create. - This corresponds to the ``test_case`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, test_case]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_test_case.CreateTestCaseRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if test_case is not None: - request.test_case = test_case - - # 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_test_case, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_test_case(self, - request: gcdc_test_case.UpdateTestCaseRequest = None, - *, - test_case: gcdc_test_case.TestCase = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_test_case.TestCase: - r"""Updates the specified test case. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateTestCaseRequest`): - The request object. The request message for - [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.UpdateTestCase]. - test_case (:class:`google.cloud.dialogflowcx_v3beta1.types.TestCase`): - Required. The test case to update. - This corresponds to the ``test_case`` 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 should be - updated. The - [``creationTime``][google.cloud.dialogflow.cx.v3beta1.TestCase.creation_time] - and - [``lastTestResult``][google.cloud.dialogflow.cx.v3beta1.TestCase.last_test_result] - cannot 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.dialogflowcx_v3beta1.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([test_case, 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 = gcdc_test_case.UpdateTestCaseRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if test_case is not None: - request.test_case = test_case - if update_mask is not None: - 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_test_case, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("test_case.name", request.test_case.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_test_case(self, - request: test_case.RunTestCaseRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Kicks off a test case run. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.RunTestCaseRequest`): - The request object. The request message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.RunTestCaseResponse` - The response message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. - - """ - # Create or coerce a protobuf request object. - request = test_case.RunTestCaseRequest(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.run_test_case, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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, - test_case.RunTestCaseResponse, - metadata_type=test_case.RunTestCaseMetadata, - ) - - # Done; return the response. - return response - - async def batch_run_test_cases(self, - request: test_case.BatchRunTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Kicks off a batch run of test cases. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesRequest`): - The request object. The request message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesResponse` - The response message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. - - """ - # Create or coerce a protobuf request object. - request = test_case.BatchRunTestCasesRequest(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_run_test_cases, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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, - test_case.BatchRunTestCasesResponse, - metadata_type=test_case.BatchRunTestCasesMetadata, - ) - - # Done; return the response. - return response - - async def calculate_coverage(self, - request: test_case.CalculateCoverageRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.CalculateCoverageResponse: - r"""Calculates the test coverage for an agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageRequest`): - The request object. The request message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageResponse: - The response message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. - - """ - # Create or coerce a protobuf request object. - request = test_case.CalculateCoverageRequest(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.calculate_coverage, - default_timeout=None, - client_info=DEFAULT_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", request.agent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_test_cases(self, - request: test_case.ImportTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesRequest`): - The request object. The request message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesResponse` - The response message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. - - """ - # Create or coerce a protobuf request object. - request = test_case.ImportTestCasesRequest(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_test_cases, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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, - test_case.ImportTestCasesResponse, - metadata_type=test_case.ImportTestCasesMetadata, - ) - - # Done; return the response. - return response - - async def export_test_cases(self, - request: test_case.ExportTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest`): - The request object. The request message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesResponse` - The response message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. - - """ - # Create or coerce a protobuf request object. - request = test_case.ExportTestCasesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_test_cases, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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, - test_case.ExportTestCasesResponse, - metadata_type=test_case.ExportTestCasesMetadata, - ) - - # Done; return the response. - return response - - async def list_test_case_results(self, - request: test_case.ListTestCaseResultsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTestCaseResultsAsyncPager: - r"""Fetches a list of results for a given test case. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsRequest`): - The request object. The request message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. - parent (:class:`str`): - Required. The test case to list results for. Format: - ``projects//locations//agents// testCases/``. - Specify a ``-`` as a wildcard for TestCase ID to list - results across multiple test cases. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers.ListTestCaseResultsAsyncPager: - The response message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. - - 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 = test_case.ListTestCaseResultsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_test_case_results, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListTestCaseResultsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_test_case_result(self, - request: test_case.GetTestCaseResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.TestCaseResult: - r"""Gets a test case result. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetTestCaseResultRequest`): - The request object. The request message for - [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCaseResult]. - name (:class:`str`): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases//results/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.TestCaseResult: - Represents a result from running a - test case in an agent environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = test_case.GetTestCaseResultRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_test_case_result, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "TestCasesAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py deleted file mode 100644 index f42b5eb8..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py +++ /dev/null @@ -1,1346 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.test_cases import pagers -from google.cloud.dialogflowcx_v3beta1.types import test_case -from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TestCasesGrpcTransport -from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport - - -class TestCasesClientMeta(type): - """Metaclass for the TestCases 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[TestCasesTransport]] - _transport_registry["grpc"] = TestCasesGrpcTransport - _transport_registry["grpc_asyncio"] = TestCasesGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[TestCasesTransport]: - """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 TestCasesClient(metaclass=TestCasesClientMeta): - """Service for managing [Test - Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and [Test Case - Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult]. - """ - - @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: - TestCasesClient: 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: - TestCasesClient: 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) -> TestCasesTransport: - """Returns the transport used by the client instance. - - Returns: - TestCasesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def agent_path(project: str,location: str,agent: str,) -> str: - """Returns a fully-qualified agent string.""" - return "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) - - @staticmethod - def parse_agent_path(path: str) -> Dict[str,str]: - """Parses a agent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def entity_type_path(project: str,location: str,agent: str,entity_type: str,) -> str: - """Returns a fully-qualified entity_type string.""" - return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - - @staticmethod - def parse_entity_type_path(path: str) -> Dict[str,str]: - """Parses a entity_type path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def environment_path(project: str,location: str,agent: str,environment: str,) -> str: - """Returns a fully-qualified environment string.""" - return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - - @staticmethod - def parse_environment_path(path: str) -> Dict[str,str]: - """Parses a environment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: - """Returns a fully-qualified page string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - - @staticmethod - def parse_page_path(path: str) -> Dict[str,str]: - """Parses a page path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def test_case_path(project: str,location: str,agent: str,test_case: str,) -> str: - """Returns a fully-qualified test_case string.""" - return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(project=project, location=location, agent=agent, test_case=test_case, ) - - @staticmethod - def parse_test_case_path(path: str) -> Dict[str,str]: - """Parses a test_case path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def test_case_result_path(project: str,location: str,agent: str,test_case: str,result: str,) -> str: - """Returns a fully-qualified test_case_result string.""" - return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) - - @staticmethod - def parse_test_case_result_path(path: str) -> Dict[str,str]: - """Parses a test_case_result path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: - """Returns a fully-qualified transition_route_group string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - - @staticmethod - def parse_transition_route_group_path(path: str) -> Dict[str,str]: - """Parses a transition_route_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, TestCasesTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the test cases 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, TestCasesTransport]): 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, TestCasesTransport): - # transport is a TestCasesTransport 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_test_cases(self, - request: test_case.ListTestCasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTestCasesPager: - r"""Fetches a list of test cases for a given agent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest): - The request object. The request message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. - parent (str): - Required. The agent to list all pages for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers.ListTestCasesPager: - The response message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. - - 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 test_case.ListTestCasesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.ListTestCasesRequest): - request = test_case.ListTestCasesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_test_cases] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListTestCasesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_delete_test_cases(self, - request: test_case.BatchDeleteTestCasesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Batch deletes test cases. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.BatchDeleteTestCasesRequest): - The request object. The request message for - [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchDeleteTestCases]. - parent (str): - Required. The agent to delete test cases from. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 test_case.BatchDeleteTestCasesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.BatchDeleteTestCasesRequest): - request = test_case.BatchDeleteTestCasesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_delete_test_cases] - - # Certain fields should be 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 get_test_case(self, - request: test_case.GetTestCaseRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.TestCase: - r"""Gets a test case. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetTestCaseRequest): - The request object. The request message for - [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCase]. - name (str): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a test_case.GetTestCaseRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.GetTestCaseRequest): - request = test_case.GetTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_test_case] - - # Certain fields should be provided 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_test_case(self, - request: gcdc_test_case.CreateTestCaseRequest = None, - *, - parent: str = None, - test_case: gcdc_test_case.TestCase = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_test_case.TestCase: - r"""Creates a test case for the given agent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateTestCaseRequest): - The request object. The request message for - [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.CreateTestCase]. - parent (str): - Required. The agent to create the test case for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): - Required. The test case to create. - This corresponds to the ``test_case`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, test_case]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_test_case.CreateTestCaseRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_test_case.CreateTestCaseRequest): - request = gcdc_test_case.CreateTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if test_case is not None: - request.test_case = test_case - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_test_case] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_test_case(self, - request: gcdc_test_case.UpdateTestCaseRequest = None, - *, - test_case: gcdc_test_case.TestCase = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_test_case.TestCase: - r"""Updates the specified test case. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateTestCaseRequest): - The request object. The request message for - [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.UpdateTestCase]. - test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): - Required. The test case to update. - This corresponds to the ``test_case`` 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 should be - updated. The - [``creationTime``][google.cloud.dialogflow.cx.v3beta1.TestCase.creation_time] - and - [``lastTestResult``][google.cloud.dialogflow.cx.v3beta1.TestCase.last_test_result] - cannot 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.dialogflowcx_v3beta1.types.TestCase: - Represents a test case. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([test_case, 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 gcdc_test_case.UpdateTestCaseRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_test_case.UpdateTestCaseRequest): - request = gcdc_test_case.UpdateTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if test_case is not None: - request.test_case = test_case - if update_mask is not None: - 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_test_case] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("test_case.name", request.test_case.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_test_case(self, - request: test_case.RunTestCaseRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Kicks off a test case run. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.RunTestCaseRequest): - The request object. The request message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.RunTestCaseResponse` - The response message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a test_case.RunTestCaseRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.RunTestCaseRequest): - request = test_case.RunTestCaseRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_test_case] - - # Certain fields should be provided 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, - test_case.RunTestCaseResponse, - metadata_type=test_case.RunTestCaseMetadata, - ) - - # Done; return the response. - return response - - def batch_run_test_cases(self, - request: test_case.BatchRunTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Kicks off a batch run of test cases. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesRequest): - The request object. The request message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesResponse` - The response message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a test_case.BatchRunTestCasesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.BatchRunTestCasesRequest): - request = test_case.BatchRunTestCasesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_run_test_cases] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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, - test_case.BatchRunTestCasesResponse, - metadata_type=test_case.BatchRunTestCasesMetadata, - ) - - # Done; return the response. - return response - - def calculate_coverage(self, - request: test_case.CalculateCoverageRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.CalculateCoverageResponse: - r"""Calculates the test coverage for an agent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageRequest): - The request object. The request message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageResponse: - The response message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a test_case.CalculateCoverageRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.CalculateCoverageRequest): - request = test_case.CalculateCoverageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.calculate_coverage] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("agent", request.agent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_test_cases(self, - request: test_case.ImportTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesRequest): - The request object. The request message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesResponse` - The response message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a test_case.ImportTestCasesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.ImportTestCasesRequest): - request = test_case.ImportTestCasesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_test_cases] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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, - test_case.ImportTestCasesResponse, - metadata_type=test_case.ImportTestCasesMetadata, - ) - - # Done; return the response. - return response - - def export_test_cases(self, - request: test_case.ExportTestCasesRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest): - The request object. The request message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesResponse` - The response message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a test_case.ExportTestCasesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.ExportTestCasesRequest): - request = test_case.ExportTestCasesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_test_cases] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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, - test_case.ExportTestCasesResponse, - metadata_type=test_case.ExportTestCasesMetadata, - ) - - # Done; return the response. - return response - - def list_test_case_results(self, - request: test_case.ListTestCaseResultsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTestCaseResultsPager: - r"""Fetches a list of results for a given test case. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsRequest): - The request object. The request message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. - parent (str): - Required. The test case to list results for. Format: - ``projects//locations//agents// testCases/``. - Specify a ``-`` as a wildcard for TestCase ID to list - results across multiple test cases. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers.ListTestCaseResultsPager: - The response message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. - - 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 test_case.ListTestCaseResultsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.ListTestCaseResultsRequest): - request = test_case.ListTestCaseResultsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_test_case_results] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListTestCaseResultsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_test_case_result(self, - request: test_case.GetTestCaseResultRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> test_case.TestCaseResult: - r"""Gets a test case result. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetTestCaseResultRequest): - The request object. The request message for - [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCaseResult]. - name (str): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases//results/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.TestCaseResult: - Represents a result from running a - test case in an agent environment. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a test_case.GetTestCaseResultRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, test_case.GetTestCaseResultRequest): - request = test_case.GetTestCaseResultRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_test_case_result] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "TestCasesClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py deleted file mode 100644 index 1d7f479e..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/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.dialogflowcx_v3beta1.types import test_case - - -class ListTestCasesPager: - """A pager for iterating through ``list_test_cases`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``test_cases`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTestCases`` requests and continue to iterate - through the ``test_cases`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse` - 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[..., test_case.ListTestCasesResponse], - request: test_case.ListTestCasesRequest, - response: test_case.ListTestCasesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse): - 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 = test_case.ListTestCasesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[test_case.ListTestCasesResponse]: - 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[test_case.TestCase]: - for page in self.pages: - yield from page.test_cases - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTestCasesAsyncPager: - """A pager for iterating through ``list_test_cases`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``test_cases`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTestCases`` requests and continue to iterate - through the ``test_cases`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse` - 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[test_case.ListTestCasesResponse]], - request: test_case.ListTestCasesRequest, - response: test_case.ListTestCasesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesResponse): - 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 = test_case.ListTestCasesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[test_case.ListTestCasesResponse]: - 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[test_case.TestCase]: - async def async_generator(): - async for page in self.pages: - for response in page.test_cases: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTestCaseResultsPager: - """A pager for iterating through ``list_test_case_results`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``test_case_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTestCaseResults`` requests and continue to iterate - through the ``test_case_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse` - 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[..., test_case.ListTestCaseResultsResponse], - request: test_case.ListTestCaseResultsRequest, - response: test_case.ListTestCaseResultsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse): - 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 = test_case.ListTestCaseResultsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[test_case.ListTestCaseResultsResponse]: - 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[test_case.TestCaseResult]: - for page in self.pages: - yield from page.test_case_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTestCaseResultsAsyncPager: - """A pager for iterating through ``list_test_case_results`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``test_case_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTestCaseResults`` requests and continue to iterate - through the ``test_case_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse` - 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[test_case.ListTestCaseResultsResponse]], - request: test_case.ListTestCaseResultsRequest, - response: test_case.ListTestCaseResultsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListTestCaseResultsResponse): - 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 = test_case.ListTestCaseResultsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[test_case.ListTestCaseResultsResponse]: - 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[test_case.TestCaseResult]: - async def async_generator(): - async for page in self.pages: - for response in page.test_case_results: - 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py deleted file mode 100644 index 52d2730d..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/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 TestCasesTransport -from .grpc import TestCasesGrpcTransport -from .grpc_asyncio import TestCasesGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TestCasesTransport]] -_transport_registry['grpc'] = TestCasesGrpcTransport -_transport_registry['grpc_asyncio'] = TestCasesGrpcAsyncIOTransport - -__all__ = ( - 'TestCasesTransport', - 'TestCasesGrpcTransport', - 'TestCasesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py deleted file mode 100644 index d6644a12..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py +++ /dev/null @@ -1,346 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import test_case -from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 # 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-dialogflowcx', - ).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 TestCasesTransport(abc.ABC): - """Abstract transport class for TestCases.""" - - 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_test_cases: gapic_v1.method.wrap_method( - self.list_test_cases, - default_timeout=None, - client_info=client_info, - ), - self.batch_delete_test_cases: gapic_v1.method.wrap_method( - self.batch_delete_test_cases, - default_timeout=None, - client_info=client_info, - ), - self.get_test_case: gapic_v1.method.wrap_method( - self.get_test_case, - default_timeout=None, - client_info=client_info, - ), - self.create_test_case: gapic_v1.method.wrap_method( - self.create_test_case, - default_timeout=None, - client_info=client_info, - ), - self.update_test_case: gapic_v1.method.wrap_method( - self.update_test_case, - default_timeout=None, - client_info=client_info, - ), - self.run_test_case: gapic_v1.method.wrap_method( - self.run_test_case, - default_timeout=None, - client_info=client_info, - ), - self.batch_run_test_cases: gapic_v1.method.wrap_method( - self.batch_run_test_cases, - default_timeout=None, - client_info=client_info, - ), - self.calculate_coverage: gapic_v1.method.wrap_method( - self.calculate_coverage, - default_timeout=None, - client_info=client_info, - ), - self.import_test_cases: gapic_v1.method.wrap_method( - self.import_test_cases, - default_timeout=None, - client_info=client_info, - ), - self.export_test_cases: gapic_v1.method.wrap_method( - self.export_test_cases, - default_timeout=None, - client_info=client_info, - ), - self.list_test_case_results: gapic_v1.method.wrap_method( - self.list_test_case_results, - default_timeout=None, - client_info=client_info, - ), - self.get_test_case_result: gapic_v1.method.wrap_method( - self.get_test_case_result, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_test_cases(self) -> Callable[ - [test_case.ListTestCasesRequest], - Union[ - test_case.ListTestCasesResponse, - Awaitable[test_case.ListTestCasesResponse] - ]]: - raise NotImplementedError() - - @property - def batch_delete_test_cases(self) -> Callable[ - [test_case.BatchDeleteTestCasesRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def get_test_case(self) -> Callable[ - [test_case.GetTestCaseRequest], - Union[ - test_case.TestCase, - Awaitable[test_case.TestCase] - ]]: - raise NotImplementedError() - - @property - def create_test_case(self) -> Callable[ - [gcdc_test_case.CreateTestCaseRequest], - Union[ - gcdc_test_case.TestCase, - Awaitable[gcdc_test_case.TestCase] - ]]: - raise NotImplementedError() - - @property - def update_test_case(self) -> Callable[ - [gcdc_test_case.UpdateTestCaseRequest], - Union[ - gcdc_test_case.TestCase, - Awaitable[gcdc_test_case.TestCase] - ]]: - raise NotImplementedError() - - @property - def run_test_case(self) -> Callable[ - [test_case.RunTestCaseRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def batch_run_test_cases(self) -> Callable[ - [test_case.BatchRunTestCasesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def calculate_coverage(self) -> Callable[ - [test_case.CalculateCoverageRequest], - Union[ - test_case.CalculateCoverageResponse, - Awaitable[test_case.CalculateCoverageResponse] - ]]: - raise NotImplementedError() - - @property - def import_test_cases(self) -> Callable[ - [test_case.ImportTestCasesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_test_cases(self) -> Callable[ - [test_case.ExportTestCasesRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_test_case_results(self) -> Callable[ - [test_case.ListTestCaseResultsRequest], - Union[ - test_case.ListTestCaseResultsResponse, - Awaitable[test_case.ListTestCaseResultsResponse] - ]]: - raise NotImplementedError() - - @property - def get_test_case_result(self) -> Callable[ - [test_case.GetTestCaseResultRequest], - Union[ - test_case.TestCaseResult, - Awaitable[test_case.TestCaseResult] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'TestCasesTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py deleted file mode 100644 index 97c6b359..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py +++ /dev/null @@ -1,562 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import test_case -from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import TestCasesTransport, DEFAULT_CLIENT_INFO - - -class TestCasesGrpcTransport(TestCasesTransport): - """gRPC backend transport for TestCases. - - Service for managing [Test - Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and [Test Case - Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult]. - - 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_test_cases(self) -> Callable[ - [test_case.ListTestCasesRequest], - test_case.ListTestCasesResponse]: - r"""Return a callable for the list test cases method over gRPC. - - Fetches a list of test cases for a given agent. - - Returns: - Callable[[~.ListTestCasesRequest], - ~.ListTestCasesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_test_cases' not in self._stubs: - self._stubs['list_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/ListTestCases', - request_serializer=test_case.ListTestCasesRequest.serialize, - response_deserializer=test_case.ListTestCasesResponse.deserialize, - ) - return self._stubs['list_test_cases'] - - @property - def batch_delete_test_cases(self) -> Callable[ - [test_case.BatchDeleteTestCasesRequest], - empty_pb2.Empty]: - r"""Return a callable for the batch delete test cases method over gRPC. - - Batch deletes test cases. - - Returns: - Callable[[~.BatchDeleteTestCasesRequest], - ~.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 'batch_delete_test_cases' not in self._stubs: - self._stubs['batch_delete_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchDeleteTestCases', - request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['batch_delete_test_cases'] - - @property - def get_test_case(self) -> Callable[ - [test_case.GetTestCaseRequest], - test_case.TestCase]: - r"""Return a callable for the get test case method over gRPC. - - Gets a test case. - - Returns: - Callable[[~.GetTestCaseRequest], - ~.TestCase]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_test_case' not in self._stubs: - self._stubs['get_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCase', - request_serializer=test_case.GetTestCaseRequest.serialize, - response_deserializer=test_case.TestCase.deserialize, - ) - return self._stubs['get_test_case'] - - @property - def create_test_case(self) -> Callable[ - [gcdc_test_case.CreateTestCaseRequest], - gcdc_test_case.TestCase]: - r"""Return a callable for the create test case method over gRPC. - - Creates a test case for the given agent. - - Returns: - Callable[[~.CreateTestCaseRequest], - ~.TestCase]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_test_case' not in self._stubs: - self._stubs['create_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/CreateTestCase', - request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize, - response_deserializer=gcdc_test_case.TestCase.deserialize, - ) - return self._stubs['create_test_case'] - - @property - def update_test_case(self) -> Callable[ - [gcdc_test_case.UpdateTestCaseRequest], - gcdc_test_case.TestCase]: - r"""Return a callable for the update test case method over gRPC. - - Updates the specified test case. - - Returns: - Callable[[~.UpdateTestCaseRequest], - ~.TestCase]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_test_case' not in self._stubs: - self._stubs['update_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/UpdateTestCase', - request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize, - response_deserializer=gcdc_test_case.TestCase.deserialize, - ) - return self._stubs['update_test_case'] - - @property - def run_test_case(self) -> Callable[ - [test_case.RunTestCaseRequest], - operations_pb2.Operation]: - r"""Return a callable for the run test case method over gRPC. - - Kicks off a test case run. - - Returns: - Callable[[~.RunTestCaseRequest], - ~.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 'run_test_case' not in self._stubs: - self._stubs['run_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/RunTestCase', - request_serializer=test_case.RunTestCaseRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_test_case'] - - @property - def batch_run_test_cases(self) -> Callable[ - [test_case.BatchRunTestCasesRequest], - operations_pb2.Operation]: - r"""Return a callable for the batch run test cases method over gRPC. - - Kicks off a batch run of test cases. - - Returns: - Callable[[~.BatchRunTestCasesRequest], - ~.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_run_test_cases' not in self._stubs: - self._stubs['batch_run_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchRunTestCases', - request_serializer=test_case.BatchRunTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_run_test_cases'] - - @property - def calculate_coverage(self) -> Callable[ - [test_case.CalculateCoverageRequest], - test_case.CalculateCoverageResponse]: - r"""Return a callable for the calculate coverage method over gRPC. - - Calculates the test coverage for an agent. - - Returns: - Callable[[~.CalculateCoverageRequest], - ~.CalculateCoverageResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'calculate_coverage' not in self._stubs: - self._stubs['calculate_coverage'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/CalculateCoverage', - request_serializer=test_case.CalculateCoverageRequest.serialize, - response_deserializer=test_case.CalculateCoverageResponse.deserialize, - ) - return self._stubs['calculate_coverage'] - - @property - def import_test_cases(self) -> Callable[ - [test_case.ImportTestCasesRequest], - operations_pb2.Operation]: - r"""Return a callable for the import test cases method over gRPC. - - Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. - - Returns: - Callable[[~.ImportTestCasesRequest], - ~.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_test_cases' not in self._stubs: - self._stubs['import_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/ImportTestCases', - request_serializer=test_case.ImportTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_test_cases'] - - @property - def export_test_cases(self) -> Callable[ - [test_case.ExportTestCasesRequest], - operations_pb2.Operation]: - r"""Return a callable for the export test cases method over gRPC. - - Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. - - Returns: - Callable[[~.ExportTestCasesRequest], - ~.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_test_cases' not in self._stubs: - self._stubs['export_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/ExportTestCases', - request_serializer=test_case.ExportTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_test_cases'] - - @property - def list_test_case_results(self) -> Callable[ - [test_case.ListTestCaseResultsRequest], - test_case.ListTestCaseResultsResponse]: - r"""Return a callable for the list test case results method over gRPC. - - Fetches a list of results for a given test case. - - Returns: - Callable[[~.ListTestCaseResultsRequest], - ~.ListTestCaseResultsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_test_case_results' not in self._stubs: - self._stubs['list_test_case_results'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/ListTestCaseResults', - request_serializer=test_case.ListTestCaseResultsRequest.serialize, - response_deserializer=test_case.ListTestCaseResultsResponse.deserialize, - ) - return self._stubs['list_test_case_results'] - - @property - def get_test_case_result(self) -> Callable[ - [test_case.GetTestCaseResultRequest], - test_case.TestCaseResult]: - r"""Return a callable for the get test case result method over gRPC. - - Gets a test case result. - - Returns: - Callable[[~.GetTestCaseResultRequest], - ~.TestCaseResult]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_test_case_result' not in self._stubs: - self._stubs['get_test_case_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCaseResult', - request_serializer=test_case.GetTestCaseResultRequest.serialize, - response_deserializer=test_case.TestCaseResult.deserialize, - ) - return self._stubs['get_test_case_result'] - - -__all__ = ( - 'TestCasesGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py deleted file mode 100644 index 3323ca19..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc_asyncio.py +++ /dev/null @@ -1,566 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import test_case -from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import TestCasesTransport, DEFAULT_CLIENT_INFO -from .grpc import TestCasesGrpcTransport - - -class TestCasesGrpcAsyncIOTransport(TestCasesTransport): - """gRPC AsyncIO backend transport for TestCases. - - Service for managing [Test - Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and [Test Case - Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult]. - - 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_test_cases(self) -> Callable[ - [test_case.ListTestCasesRequest], - Awaitable[test_case.ListTestCasesResponse]]: - r"""Return a callable for the list test cases method over gRPC. - - Fetches a list of test cases for a given agent. - - Returns: - Callable[[~.ListTestCasesRequest], - Awaitable[~.ListTestCasesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_test_cases' not in self._stubs: - self._stubs['list_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/ListTestCases', - request_serializer=test_case.ListTestCasesRequest.serialize, - response_deserializer=test_case.ListTestCasesResponse.deserialize, - ) - return self._stubs['list_test_cases'] - - @property - def batch_delete_test_cases(self) -> Callable[ - [test_case.BatchDeleteTestCasesRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the batch delete test cases method over gRPC. - - Batch deletes test cases. - - Returns: - Callable[[~.BatchDeleteTestCasesRequest], - 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 'batch_delete_test_cases' not in self._stubs: - self._stubs['batch_delete_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchDeleteTestCases', - request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['batch_delete_test_cases'] - - @property - def get_test_case(self) -> Callable[ - [test_case.GetTestCaseRequest], - Awaitable[test_case.TestCase]]: - r"""Return a callable for the get test case method over gRPC. - - Gets a test case. - - Returns: - Callable[[~.GetTestCaseRequest], - Awaitable[~.TestCase]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_test_case' not in self._stubs: - self._stubs['get_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCase', - request_serializer=test_case.GetTestCaseRequest.serialize, - response_deserializer=test_case.TestCase.deserialize, - ) - return self._stubs['get_test_case'] - - @property - def create_test_case(self) -> Callable[ - [gcdc_test_case.CreateTestCaseRequest], - Awaitable[gcdc_test_case.TestCase]]: - r"""Return a callable for the create test case method over gRPC. - - Creates a test case for the given agent. - - Returns: - Callable[[~.CreateTestCaseRequest], - Awaitable[~.TestCase]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_test_case' not in self._stubs: - self._stubs['create_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/CreateTestCase', - request_serializer=gcdc_test_case.CreateTestCaseRequest.serialize, - response_deserializer=gcdc_test_case.TestCase.deserialize, - ) - return self._stubs['create_test_case'] - - @property - def update_test_case(self) -> Callable[ - [gcdc_test_case.UpdateTestCaseRequest], - Awaitable[gcdc_test_case.TestCase]]: - r"""Return a callable for the update test case method over gRPC. - - Updates the specified test case. - - Returns: - Callable[[~.UpdateTestCaseRequest], - Awaitable[~.TestCase]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_test_case' not in self._stubs: - self._stubs['update_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/UpdateTestCase', - request_serializer=gcdc_test_case.UpdateTestCaseRequest.serialize, - response_deserializer=gcdc_test_case.TestCase.deserialize, - ) - return self._stubs['update_test_case'] - - @property - def run_test_case(self) -> Callable[ - [test_case.RunTestCaseRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run test case method over gRPC. - - Kicks off a test case run. - - Returns: - Callable[[~.RunTestCaseRequest], - 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 'run_test_case' not in self._stubs: - self._stubs['run_test_case'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/RunTestCase', - request_serializer=test_case.RunTestCaseRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_test_case'] - - @property - def batch_run_test_cases(self) -> Callable[ - [test_case.BatchRunTestCasesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the batch run test cases method over gRPC. - - Kicks off a batch run of test cases. - - Returns: - Callable[[~.BatchRunTestCasesRequest], - 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_run_test_cases' not in self._stubs: - self._stubs['batch_run_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchRunTestCases', - request_serializer=test_case.BatchRunTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['batch_run_test_cases'] - - @property - def calculate_coverage(self) -> Callable[ - [test_case.CalculateCoverageRequest], - Awaitable[test_case.CalculateCoverageResponse]]: - r"""Return a callable for the calculate coverage method over gRPC. - - Calculates the test coverage for an agent. - - Returns: - Callable[[~.CalculateCoverageRequest], - Awaitable[~.CalculateCoverageResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'calculate_coverage' not in self._stubs: - self._stubs['calculate_coverage'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/CalculateCoverage', - request_serializer=test_case.CalculateCoverageRequest.serialize, - response_deserializer=test_case.CalculateCoverageResponse.deserialize, - ) - return self._stubs['calculate_coverage'] - - @property - def import_test_cases(self) -> Callable[ - [test_case.ImportTestCasesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import test cases method over gRPC. - - Imports the test cases from a Cloud Storage bucket or - a local file. It always creates new test cases and won't - overwite any existing ones. The provided ID in the - imported test case is neglected. - - Returns: - Callable[[~.ImportTestCasesRequest], - 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_test_cases' not in self._stubs: - self._stubs['import_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/ImportTestCases', - request_serializer=test_case.ImportTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_test_cases'] - - @property - def export_test_cases(self) -> Callable[ - [test_case.ExportTestCasesRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the export test cases method over gRPC. - - Exports the test cases under the agent to a Cloud - Storage bucket or a local file. Filter can be applied to - export a subset of test cases. - - Returns: - Callable[[~.ExportTestCasesRequest], - 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_test_cases' not in self._stubs: - self._stubs['export_test_cases'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/ExportTestCases', - request_serializer=test_case.ExportTestCasesRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_test_cases'] - - @property - def list_test_case_results(self) -> Callable[ - [test_case.ListTestCaseResultsRequest], - Awaitable[test_case.ListTestCaseResultsResponse]]: - r"""Return a callable for the list test case results method over gRPC. - - Fetches a list of results for a given test case. - - Returns: - Callable[[~.ListTestCaseResultsRequest], - Awaitable[~.ListTestCaseResultsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_test_case_results' not in self._stubs: - self._stubs['list_test_case_results'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/ListTestCaseResults', - request_serializer=test_case.ListTestCaseResultsRequest.serialize, - response_deserializer=test_case.ListTestCaseResultsResponse.deserialize, - ) - return self._stubs['list_test_case_results'] - - @property - def get_test_case_result(self) -> Callable[ - [test_case.GetTestCaseResultRequest], - Awaitable[test_case.TestCaseResult]]: - r"""Return a callable for the get test case result method over gRPC. - - Gets a test case result. - - Returns: - Callable[[~.GetTestCaseResultRequest], - Awaitable[~.TestCaseResult]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_test_case_result' not in self._stubs: - self._stubs['get_test_case_result'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCaseResult', - request_serializer=test_case.GetTestCaseResultRequest.serialize, - response_deserializer=test_case.TestCaseResult.deserialize, - ) - return self._stubs['get_test_case_result'] - - -__all__ = ( - 'TestCasesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py deleted file mode 100644 index 8e43702f..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__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 TransitionRouteGroupsClient -from .async_client import TransitionRouteGroupsAsyncClient - -__all__ = ( - 'TransitionRouteGroupsClient', - 'TransitionRouteGroupsAsyncClient', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py deleted file mode 100644 index 0012852d..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/async_client.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.transition_route_groups import pagers -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport -from .client import TransitionRouteGroupsClient - - -class TransitionRouteGroupsAsyncClient: - """Service for managing - [TransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - """ - - _client: TransitionRouteGroupsClient - - DEFAULT_ENDPOINT = TransitionRouteGroupsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TransitionRouteGroupsClient.DEFAULT_MTLS_ENDPOINT - - flow_path = staticmethod(TransitionRouteGroupsClient.flow_path) - parse_flow_path = staticmethod(TransitionRouteGroupsClient.parse_flow_path) - intent_path = staticmethod(TransitionRouteGroupsClient.intent_path) - parse_intent_path = staticmethod(TransitionRouteGroupsClient.parse_intent_path) - page_path = staticmethod(TransitionRouteGroupsClient.page_path) - parse_page_path = staticmethod(TransitionRouteGroupsClient.parse_page_path) - transition_route_group_path = staticmethod(TransitionRouteGroupsClient.transition_route_group_path) - parse_transition_route_group_path = staticmethod(TransitionRouteGroupsClient.parse_transition_route_group_path) - webhook_path = staticmethod(TransitionRouteGroupsClient.webhook_path) - parse_webhook_path = staticmethod(TransitionRouteGroupsClient.parse_webhook_path) - common_billing_account_path = staticmethod(TransitionRouteGroupsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TransitionRouteGroupsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TransitionRouteGroupsClient.common_folder_path) - parse_common_folder_path = staticmethod(TransitionRouteGroupsClient.parse_common_folder_path) - common_organization_path = staticmethod(TransitionRouteGroupsClient.common_organization_path) - parse_common_organization_path = staticmethod(TransitionRouteGroupsClient.parse_common_organization_path) - common_project_path = staticmethod(TransitionRouteGroupsClient.common_project_path) - parse_common_project_path = staticmethod(TransitionRouteGroupsClient.parse_common_project_path) - common_location_path = staticmethod(TransitionRouteGroupsClient.common_location_path) - parse_common_location_path = staticmethod(TransitionRouteGroupsClient.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: - TransitionRouteGroupsAsyncClient: The constructed client. - """ - return TransitionRouteGroupsClient.from_service_account_info.__func__(TransitionRouteGroupsAsyncClient, 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: - TransitionRouteGroupsAsyncClient: The constructed client. - """ - return TransitionRouteGroupsClient.from_service_account_file.__func__(TransitionRouteGroupsAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> TransitionRouteGroupsTransport: - """Returns the transport used by the client instance. - - Returns: - TransitionRouteGroupsTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(TransitionRouteGroupsClient).get_transport_class, type(TransitionRouteGroupsClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, TransitionRouteGroupsTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the transition route groups 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, ~.TransitionRouteGroupsTransport]): 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 = TransitionRouteGroupsClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_transition_route_groups(self, - request: transition_route_group.ListTransitionRouteGroupsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTransitionRouteGroupsAsyncPager: - r"""Returns the list of all transition route groups in - the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsRequest`): - The request object. The request message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. - parent (:class:`str`): - Required. The flow to list all transition route groups - for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.pagers.ListTransitionRouteGroupsAsyncPager: - The response message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. - - 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # 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_transition_route_groups, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListTransitionRouteGroupsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_transition_route_group(self, - request: transition_route_group.GetTransitionRouteGroupRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transition_route_group.TransitionRouteGroup: - r"""Retrieves the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetTransitionRouteGroupRequest`): - The request object. The request message for - [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.GetTransitionRouteGroup]. - name (:class:`str`): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3beta1.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = transition_route_group.GetTransitionRouteGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_transition_route_group, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_transition_route_group(self, - request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, - *, - parent: str = None, - transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_transition_route_group.TransitionRouteGroup: - r"""Creates an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - in the specified flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateTransitionRouteGroupRequest`): - The request object. The request message for - [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.CreateTransitionRouteGroup]. - parent (:class:`str`): - Required. The flow to create an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - transition_route_group (:class:`google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup`): - Required. The transition route group - to create. - - This corresponds to the ``transition_route_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3beta1.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, transition_route_group]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if transition_route_group is not None: - request.transition_route_group = transition_route_group - - # 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_transition_route_group, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_transition_route_group(self, - request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, - *, - transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_transition_route_group.TransitionRouteGroup: - r"""Updates the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateTransitionRouteGroupRequest`): - The request object. The request message for - [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.UpdateTransitionRouteGroup]. - transition_route_group (:class:`google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup`): - Required. The transition route group - to update. - - This corresponds to the ``transition_route_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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.dialogflowcx_v3beta1.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3beta1.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([transition_route_group, 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 = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if transition_route_group is not None: - request.transition_route_group = transition_route_group - if update_mask is not None: - 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_transition_route_group, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("transition_route_group.name", request.transition_route_group.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_transition_route_group(self, - request: transition_route_group.DeleteTransitionRouteGroupRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteTransitionRouteGroupRequest`): - The request object. The request message for - [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.DeleteTransitionRouteGroup]. - name (:class:`str`): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - to delete. Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = transition_route_group.DeleteTransitionRouteGroupRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # 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_transition_route_group, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "TransitionRouteGroupsAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py deleted file mode 100644 index 5e543b07..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/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.dialogflowcx_v3beta1.services.transition_route_groups import pagers -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TransitionRouteGroupsGrpcTransport -from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport - - -class TransitionRouteGroupsClientMeta(type): - """Metaclass for the TransitionRouteGroups 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[TransitionRouteGroupsTransport]] - _transport_registry["grpc"] = TransitionRouteGroupsGrpcTransport - _transport_registry["grpc_asyncio"] = TransitionRouteGroupsGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[TransitionRouteGroupsTransport]: - """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 TransitionRouteGroupsClient(metaclass=TransitionRouteGroupsClientMeta): - """Service for managing - [TransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - """ - - @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: - TransitionRouteGroupsClient: 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: - TransitionRouteGroupsClient: 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) -> TransitionRouteGroupsTransport: - """Returns the transport used by the client instance. - - Returns: - TransitionRouteGroupsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def flow_path(project: str,location: str,agent: str,flow: str,) -> str: - """Returns a fully-qualified flow string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - - @staticmethod - def parse_flow_path(path: str) -> Dict[str,str]: - """Parses a flow path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def intent_path(project: str,location: str,agent: str,intent: str,) -> str: - """Returns a fully-qualified intent string.""" - return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - - @staticmethod - def parse_intent_path(path: str) -> Dict[str,str]: - """Parses a intent path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def page_path(project: str,location: str,agent: str,flow: str,page: str,) -> str: - """Returns a fully-qualified page string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - - @staticmethod - def parse_page_path(path: str) -> Dict[str,str]: - """Parses a page path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def transition_route_group_path(project: str,location: str,agent: str,flow: str,transition_route_group: str,) -> str: - """Returns a fully-qualified transition_route_group string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - - @staticmethod - def parse_transition_route_group_path(path: str) -> Dict[str,str]: - """Parses a transition_route_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, TransitionRouteGroupsTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the transition route groups 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, TransitionRouteGroupsTransport]): 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, TransitionRouteGroupsTransport): - # transport is a TransitionRouteGroupsTransport 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_transition_route_groups(self, - request: transition_route_group.ListTransitionRouteGroupsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTransitionRouteGroupsPager: - r"""Returns the list of all transition route groups in - the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsRequest): - The request object. The request message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. - parent (str): - Required. The flow to list all transition route groups - for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.pagers.ListTransitionRouteGroupsPager: - The response message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. - - 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 transition_route_group.ListTransitionRouteGroupsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, transition_route_group.ListTransitionRouteGroupsRequest): - request = transition_route_group.ListTransitionRouteGroupsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_transition_route_groups] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListTransitionRouteGroupsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_transition_route_group(self, - request: transition_route_group.GetTransitionRouteGroupRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> transition_route_group.TransitionRouteGroup: - r"""Retrieves the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetTransitionRouteGroupRequest): - The request object. The request message for - [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.GetTransitionRouteGroup]. - name (str): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3beta1.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 transition_route_group.GetTransitionRouteGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, transition_route_group.GetTransitionRouteGroupRequest): - request = transition_route_group.GetTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_transition_route_group] - - # Certain fields should be provided 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_transition_route_group(self, - request: gcdc_transition_route_group.CreateTransitionRouteGroupRequest = None, - *, - parent: str = None, - transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_transition_route_group.TransitionRouteGroup: - r"""Creates an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - in the specified flow. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateTransitionRouteGroupRequest): - The request object. The request message for - [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.CreateTransitionRouteGroup]. - parent (str): - Required. The flow to create an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - transition_route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): - Required. The transition route group - to create. - - This corresponds to the ``transition_route_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3beta1.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, transition_route_group]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_transition_route_group.CreateTransitionRouteGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_transition_route_group.CreateTransitionRouteGroupRequest): - request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if transition_route_group is not None: - request.transition_route_group = transition_route_group - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_transition_route_group] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_transition_route_group(self, - request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, - *, - transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_transition_route_group.TransitionRouteGroup: - r"""Updates the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateTransitionRouteGroupRequest): - The request object. The request message for - [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.UpdateTransitionRouteGroup]. - transition_route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): - Required. The transition route group - to update. - - This corresponds to the ``transition_route_group`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.dialogflowcx_v3beta1.types.TransitionRouteGroup: - An TransitionRouteGroup represents a group of - [TransitionRoutes][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - to be used by a - [Page][google.cloud.dialogflow.cx.v3beta1.Page]. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([transition_route_group, 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 gcdc_transition_route_group.UpdateTransitionRouteGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): - request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if transition_route_group is not None: - request.transition_route_group = transition_route_group - if update_mask is not None: - 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_transition_route_group] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("transition_route_group.name", request.transition_route_group.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_transition_route_group(self, - request: transition_route_group.DeleteTransitionRouteGroupRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.DeleteTransitionRouteGroupRequest): - The request object. The request message for - [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.DeleteTransitionRouteGroup]. - name (str): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - to delete. Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 transition_route_group.DeleteTransitionRouteGroupRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, transition_route_group.DeleteTransitionRouteGroupRequest): - request = transition_route_group.DeleteTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_transition_route_group] - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "TransitionRouteGroupsClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py deleted file mode 100644 index 13978441..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/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.dialogflowcx_v3beta1.types import transition_route_group - - -class ListTransitionRouteGroupsPager: - """A pager for iterating through ``list_transition_route_groups`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``transition_route_groups`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTransitionRouteGroups`` requests and continue to iterate - through the ``transition_route_groups`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse` - 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[..., transition_route_group.ListTransitionRouteGroupsResponse], - request: transition_route_group.ListTransitionRouteGroupsRequest, - response: transition_route_group.ListTransitionRouteGroupsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse): - 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[transition_route_group.ListTransitionRouteGroupsResponse]: - 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[transition_route_group.TransitionRouteGroup]: - for page in self.pages: - yield from page.transition_route_groups - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTransitionRouteGroupsAsyncPager: - """A pager for iterating through ``list_transition_route_groups`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``transition_route_groups`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTransitionRouteGroups`` requests and continue to iterate - through the ``transition_route_groups`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse` - 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[transition_route_group.ListTransitionRouteGroupsResponse]], - request: transition_route_group.ListTransitionRouteGroupsRequest, - response: transition_route_group.ListTransitionRouteGroupsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListTransitionRouteGroupsResponse): - 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 = transition_route_group.ListTransitionRouteGroupsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[transition_route_group.ListTransitionRouteGroupsResponse]: - 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[transition_route_group.TransitionRouteGroup]: - async def async_generator(): - async for page in self.pages: - for response in page.transition_route_groups: - 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py deleted file mode 100644 index 50e891f2..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/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 TransitionRouteGroupsTransport -from .grpc import TransitionRouteGroupsGrpcTransport -from .grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TransitionRouteGroupsTransport]] -_transport_registry['grpc'] = TransitionRouteGroupsGrpcTransport -_transport_registry['grpc_asyncio'] = TransitionRouteGroupsGrpcAsyncIOTransport - -__all__ = ( - 'TransitionRouteGroupsTransport', - 'TransitionRouteGroupsGrpcTransport', - 'TransitionRouteGroupsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/base.py deleted file mode 100644 index e9ccb887..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/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.dialogflowcx_v3beta1.types import transition_route_group -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-dialogflowcx', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - -_API_CORE_VERSION = google.api_core.__version__ - - -class TransitionRouteGroupsTransport(abc.ABC): - """Abstract transport class for TransitionRouteGroups.""" - - 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_transition_route_groups: gapic_v1.method.wrap_method( - self.list_transition_route_groups, - default_timeout=None, - client_info=client_info, - ), - self.get_transition_route_group: gapic_v1.method.wrap_method( - self.get_transition_route_group, - default_timeout=None, - client_info=client_info, - ), - self.create_transition_route_group: gapic_v1.method.wrap_method( - self.create_transition_route_group, - default_timeout=None, - client_info=client_info, - ), - self.update_transition_route_group: gapic_v1.method.wrap_method( - self.update_transition_route_group, - default_timeout=None, - client_info=client_info, - ), - self.delete_transition_route_group: gapic_v1.method.wrap_method( - self.delete_transition_route_group, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_transition_route_groups(self) -> Callable[ - [transition_route_group.ListTransitionRouteGroupsRequest], - Union[ - transition_route_group.ListTransitionRouteGroupsResponse, - Awaitable[transition_route_group.ListTransitionRouteGroupsResponse] - ]]: - raise NotImplementedError() - - @property - def get_transition_route_group(self) -> Callable[ - [transition_route_group.GetTransitionRouteGroupRequest], - Union[ - transition_route_group.TransitionRouteGroup, - Awaitable[transition_route_group.TransitionRouteGroup] - ]]: - raise NotImplementedError() - - @property - def create_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], - Union[ - gcdc_transition_route_group.TransitionRouteGroup, - Awaitable[gcdc_transition_route_group.TransitionRouteGroup] - ]]: - raise NotImplementedError() - - @property - def update_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], - Union[ - gcdc_transition_route_group.TransitionRouteGroup, - Awaitable[gcdc_transition_route_group.TransitionRouteGroup] - ]]: - raise NotImplementedError() - - @property - def delete_transition_route_group(self) -> Callable[ - [transition_route_group.DeleteTransitionRouteGroupRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'TransitionRouteGroupsTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py deleted file mode 100644 index e67cd5a7..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py +++ /dev/null @@ -1,361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group -from google.protobuf import empty_pb2 # type: ignore -from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO - - -class TransitionRouteGroupsGrpcTransport(TransitionRouteGroupsTransport): - """gRPC backend transport for TransitionRouteGroups. - - Service for managing - [TransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - 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_transition_route_groups(self) -> Callable[ - [transition_route_group.ListTransitionRouteGroupsRequest], - transition_route_group.ListTransitionRouteGroupsResponse]: - r"""Return a callable for the list transition route groups method over gRPC. - - Returns the list of all transition route groups in - the specified flow. - - Returns: - Callable[[~.ListTransitionRouteGroupsRequest], - ~.ListTransitionRouteGroupsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_transition_route_groups' not in self._stubs: - self._stubs['list_transition_route_groups'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/ListTransitionRouteGroups', - request_serializer=transition_route_group.ListTransitionRouteGroupsRequest.serialize, - response_deserializer=transition_route_group.ListTransitionRouteGroupsResponse.deserialize, - ) - return self._stubs['list_transition_route_groups'] - - @property - def get_transition_route_group(self) -> Callable[ - [transition_route_group.GetTransitionRouteGroupRequest], - transition_route_group.TransitionRouteGroup]: - r"""Return a callable for the get transition route group method over gRPC. - - Retrieves the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Returns: - Callable[[~.GetTransitionRouteGroupRequest], - ~.TransitionRouteGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_transition_route_group' not in self._stubs: - self._stubs['get_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/GetTransitionRouteGroup', - request_serializer=transition_route_group.GetTransitionRouteGroupRequest.serialize, - response_deserializer=transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['get_transition_route_group'] - - @property - def create_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], - gcdc_transition_route_group.TransitionRouteGroup]: - r"""Return a callable for the create transition route group method over gRPC. - - Creates an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - in the specified flow. - - Returns: - Callable[[~.CreateTransitionRouteGroupRequest], - ~.TransitionRouteGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: - self._stubs['create_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/CreateTransitionRouteGroup', - request_serializer=gcdc_transition_route_group.CreateTransitionRouteGroupRequest.serialize, - response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['create_transition_route_group'] - - @property - def update_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], - gcdc_transition_route_group.TransitionRouteGroup]: - r"""Return a callable for the update transition route group method over gRPC. - - Updates the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Returns: - Callable[[~.UpdateTransitionRouteGroupRequest], - ~.TransitionRouteGroup]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: - self._stubs['update_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/UpdateTransitionRouteGroup', - request_serializer=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.serialize, - response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['update_transition_route_group'] - - @property - def delete_transition_route_group(self) -> Callable[ - [transition_route_group.DeleteTransitionRouteGroupRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete transition route group method over gRPC. - - Deletes the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Returns: - Callable[[~.DeleteTransitionRouteGroupRequest], - ~.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_transition_route_group' not in self._stubs: - self._stubs['delete_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/DeleteTransitionRouteGroup', - request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_transition_route_group'] - - -__all__ = ( - 'TransitionRouteGroupsGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py deleted file mode 100644 index ca567335..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc_asyncio.py +++ /dev/null @@ -1,365 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import transition_route_group -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group -from google.protobuf import empty_pb2 # type: ignore -from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO -from .grpc import TransitionRouteGroupsGrpcTransport - - -class TransitionRouteGroupsGrpcAsyncIOTransport(TransitionRouteGroupsTransport): - """gRPC AsyncIO backend transport for TransitionRouteGroups. - - Service for managing - [TransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - 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_transition_route_groups(self) -> Callable[ - [transition_route_group.ListTransitionRouteGroupsRequest], - Awaitable[transition_route_group.ListTransitionRouteGroupsResponse]]: - r"""Return a callable for the list transition route groups method over gRPC. - - Returns the list of all transition route groups in - the specified flow. - - Returns: - Callable[[~.ListTransitionRouteGroupsRequest], - Awaitable[~.ListTransitionRouteGroupsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_transition_route_groups' not in self._stubs: - self._stubs['list_transition_route_groups'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/ListTransitionRouteGroups', - request_serializer=transition_route_group.ListTransitionRouteGroupsRequest.serialize, - response_deserializer=transition_route_group.ListTransitionRouteGroupsResponse.deserialize, - ) - return self._stubs['list_transition_route_groups'] - - @property - def get_transition_route_group(self) -> Callable[ - [transition_route_group.GetTransitionRouteGroupRequest], - Awaitable[transition_route_group.TransitionRouteGroup]]: - r"""Return a callable for the get transition route group method over gRPC. - - Retrieves the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Returns: - Callable[[~.GetTransitionRouteGroupRequest], - Awaitable[~.TransitionRouteGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_transition_route_group' not in self._stubs: - self._stubs['get_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/GetTransitionRouteGroup', - request_serializer=transition_route_group.GetTransitionRouteGroupRequest.serialize, - response_deserializer=transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['get_transition_route_group'] - - @property - def create_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], - Awaitable[gcdc_transition_route_group.TransitionRouteGroup]]: - r"""Return a callable for the create transition route group method over gRPC. - - Creates an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - in the specified flow. - - Returns: - Callable[[~.CreateTransitionRouteGroupRequest], - Awaitable[~.TransitionRouteGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: - self._stubs['create_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/CreateTransitionRouteGroup', - request_serializer=gcdc_transition_route_group.CreateTransitionRouteGroupRequest.serialize, - response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['create_transition_route_group'] - - @property - def update_transition_route_group(self) -> Callable[ - [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], - Awaitable[gcdc_transition_route_group.TransitionRouteGroup]]: - r"""Return a callable for the update transition route group method over gRPC. - - Updates the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Returns: - Callable[[~.UpdateTransitionRouteGroupRequest], - Awaitable[~.TransitionRouteGroup]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_transition_route_group' not in self._stubs: - self._stubs['update_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/UpdateTransitionRouteGroup', - request_serializer=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest.serialize, - response_deserializer=gcdc_transition_route_group.TransitionRouteGroup.deserialize, - ) - return self._stubs['update_transition_route_group'] - - @property - def delete_transition_route_group(self) -> Callable[ - [transition_route_group.DeleteTransitionRouteGroupRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete transition route group method over gRPC. - - Deletes the specified - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - - Returns: - Callable[[~.DeleteTransitionRouteGroupRequest], - 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_transition_route_group' not in self._stubs: - self._stubs['delete_transition_route_group'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/DeleteTransitionRouteGroup', - request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_transition_route_group'] - - -__all__ = ( - 'TransitionRouteGroupsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py deleted file mode 100644 index 630246bd..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/__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 VersionsClient -from .async_client import VersionsAsyncClient - -__all__ = ( - 'VersionsClient', - 'VersionsAsyncClient', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py deleted file mode 100644 index 13a5155c..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py +++ /dev/null @@ -1,690 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.versions import pagers -from google.cloud.dialogflowcx_v3beta1.types import flow -from google.cloud.dialogflowcx_v3beta1.types import version -from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport -from .client import VersionsClient - - -class VersionsAsyncClient: - """Service for managing - [Versions][google.cloud.dialogflow.cx.v3beta1.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 in the specified - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListVersionsRequest`): - The request object. The request message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.Versions.ListVersions]. - parent (:class:`str`): - Required. The - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to list - all versions for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.versions.pagers.ListVersionsAsyncPager: - The response message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.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 - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetVersionRequest`): - The request object. The request message for - [Versions.GetVersion][google.cloud.dialogflow.cx.v3beta1.Versions.GetVersion]. - name (:class:`str`): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Version: - Represents a version of a flow. - """ - # Create or coerce a protobuf request object. - # Sanity check: 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: gcdc_version.CreateVersionRequest = None, - *, - parent: str = None, - version: gcdc_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a [Version][google.cloud.dialogflow.cx.v3beta1.Version] - in the specified - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateVersionRequest`): - The request object. The request message for - [Versions.CreateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.CreateVersion]. - parent (:class:`str`): - Required. The - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to - create an - [Version][google.cloud.dialogflow.cx.v3beta1.Version] - for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - version (:class:`google.cloud.dialogflowcx_v3beta1.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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.Version` - Represents a version of a flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = gcdc_version.CreateVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if version is not None: - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcdc_version.Version, - metadata_type=gcdc_version.CreateVersionOperationMetadata, - ) - - # Done; return the response. - return response - - async def update_version(self, - request: gcdc_version.UpdateVersionRequest = None, - *, - version: gcdc_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]] = (), - ) -> gcdc_version.Version: - r"""Updates the specified - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateVersionRequest`): - The request object. The request message for - [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.UpdateVersion]. - version (:class:`google.cloud.dialogflowcx_v3beta1.types.Version`): - Required. The version to update. - 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. - Currently only ``description`` and ``display_name`` can - 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.dialogflowcx_v3beta1.types.Version: - Represents a version of a flow. - """ - # Create or coerce a protobuf request object. - # Sanity 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 = gcdc_version.UpdateVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if version is not None: - request.version = version - if update_mask is not None: - 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"""Deletes the specified - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteVersionRequest`): - The request object. The request message for - [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3beta1.Versions.DeleteVersion]. - name (:class:`str`): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3beta1.Version] to - delete. Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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, - ) - - async def load_version(self, - request: version.LoadVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Loads resources in the specified version to the draft - flow. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.LoadVersionRequest`): - The request object. The request message for - [Versions.LoadVersion][google.cloud.dialogflow.cx.v3beta1.Versions.LoadVersion]. - name (:class:`str`): - Required. The - [Version][google.cloud.dialogflow.cx.v3beta1.Version] to - be loaded to draft flow. Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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 = version.LoadVersionRequest(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.load_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, - ) - - # 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VersionsAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/client.py deleted file mode 100644 index 6d70e13b..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/client.py +++ /dev/null @@ -1,877 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.versions import pagers -from google.cloud.dialogflowcx_v3beta1.types import flow -from google.cloud.dialogflowcx_v3beta1.types import version -from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import VersionsGrpcTransport -from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport - - -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.cx.v3beta1.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,location: str,agent: str,flow: str,version: str,) -> str: - """Returns a fully-qualified version string.""" - return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - - @staticmethod - def parse_version_path(path: str) -> Dict[str,str]: - """Parses a version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/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 in the specified - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListVersionsRequest): - The request object. The request message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.Versions.ListVersions]. - parent (str): - Required. The - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to list - all versions for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.versions.pagers.ListVersionsPager: - The response message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.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 - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetVersionRequest): - The request object. The request message for - [Versions.GetVersion][google.cloud.dialogflow.cx.v3beta1.Versions.GetVersion]. - name (str): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Version: - Represents a version of a flow. - """ - # Create or coerce a protobuf request object. - # Sanity check: 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: gcdc_version.CreateVersionRequest = None, - *, - parent: str = None, - version: gcdc_version.Version = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a [Version][google.cloud.dialogflow.cx.v3beta1.Version] - in the specified - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateVersionRequest): - The request object. The request message for - [Versions.CreateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.CreateVersion]. - parent (str): - Required. The - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to - create an - [Version][google.cloud.dialogflow.cx.v3beta1.Version] - for. Format: - ``projects//locations//agents//flows/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - version (google.cloud.dialogflowcx_v3beta1.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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.dialogflowcx_v3beta1.types.Version` - Represents a version of a flow. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 gcdc_version.CreateVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_version.CreateVersionRequest): - request = gcdc_version.CreateVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if version is not None: - 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcdc_version.Version, - metadata_type=gcdc_version.CreateVersionOperationMetadata, - ) - - # Done; return the response. - return response - - def update_version(self, - request: gcdc_version.UpdateVersionRequest = None, - *, - version: gcdc_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]] = (), - ) -> gcdc_version.Version: - r"""Updates the specified - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateVersionRequest): - The request object. The request message for - [Versions.UpdateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.UpdateVersion]. - version (google.cloud.dialogflowcx_v3beta1.types.Version): - Required. The version to update. - 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. - Currently only ``description`` and ``display_name`` can - 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.dialogflowcx_v3beta1.types.Version: - Represents a version of a flow. - """ - # Create or coerce a protobuf request object. - # Sanity 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 gcdc_version.UpdateVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_version.UpdateVersionRequest): - request = gcdc_version.UpdateVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if version is not None: - request.version = version - if update_mask is not None: - 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"""Deletes the specified - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.DeleteVersionRequest): - The request object. The request message for - [Versions.DeleteVersion][google.cloud.dialogflow.cx.v3beta1.Versions.DeleteVersion]. - name (str): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3beta1.Version] to - delete. Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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, - ) - - def load_version(self, - request: version.LoadVersionRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Loads resources in the specified version to the draft - flow. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.LoadVersionRequest): - The request object. The request message for - [Versions.LoadVersion][google.cloud.dialogflow.cx.v3beta1.Versions.LoadVersion]. - name (str): - Required. The - [Version][google.cloud.dialogflow.cx.v3beta1.Version] to - be loaded to draft flow. Format: - ``projects//locations//agents//flows//versions/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - 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 version.LoadVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, version.LoadVersionRequest): - request = version.LoadVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.load_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, - ) - - # 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "VersionsClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py deleted file mode 100644 index 71b9d9fa..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/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.dialogflowcx_v3beta1.types import version - - -class ListVersionsPager: - """A pager for iterating through ``list_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListVersionsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.ListVersionsRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py deleted file mode 100644 index dfb70ce9..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/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 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py deleted file mode 100644 index 88fcd66f..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.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. -# -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.dialogflowcx_v3beta1.types import version -from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version -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-dialogflowcx', - ).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, - ), - self.load_version: gapic_v1.method.wrap_method( - self.load_version, - 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_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[ - [gcdc_version.CreateVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_version(self) -> Callable[ - [gcdc_version.UpdateVersionRequest], - Union[ - gcdc_version.Version, - Awaitable[gcdc_version.Version] - ]]: - raise NotImplementedError() - - @property - def delete_version(self) -> Callable[ - [version.DeleteVersionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def load_version(self) -> Callable[ - [version.LoadVersionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'VersionsTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py deleted file mode 100644 index abf54494..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py +++ /dev/null @@ -1,407 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import version -from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version -from google.longrunning import operations_pb2 # type: ignore -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.cx.v3beta1.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] = {} - 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_versions(self) -> Callable[ - [version.ListVersionsRequest], - version.ListVersionsResponse]: - r"""Return a callable for the list versions method over gRPC. - - Returns the list of all versions in the specified - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. - - 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.cx.v3beta1.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 - [Version][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Versions/GetVersion', - request_serializer=version.GetVersionRequest.serialize, - response_deserializer=version.Version.deserialize, - ) - return self._stubs['get_version'] - - @property - def create_version(self) -> Callable[ - [gcdc_version.CreateVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create version method over gRPC. - - Creates a [Version][google.cloud.dialogflow.cx.v3beta1.Version] - in the specified - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. - - Returns: - Callable[[~.CreateVersionRequest], - ~.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_version' not in self._stubs: - self._stubs['create_version'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Versions/CreateVersion', - request_serializer=gcdc_version.CreateVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_version'] - - @property - def update_version(self) -> Callable[ - [gcdc_version.UpdateVersionRequest], - gcdc_version.Version]: - r"""Return a callable for the update version method over gRPC. - - Updates the specified - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - - 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.cx.v3beta1.Versions/UpdateVersion', - request_serializer=gcdc_version.UpdateVersionRequest.serialize, - response_deserializer=gcdc_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. - - Deletes the specified - [Version][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Versions/DeleteVersion', - request_serializer=version.DeleteVersionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_version'] - - @property - def load_version(self) -> Callable[ - [version.LoadVersionRequest], - operations_pb2.Operation]: - r"""Return a callable for the load version method over gRPC. - - Loads resources in the specified version to the draft - flow. - - Returns: - Callable[[~.LoadVersionRequest], - ~.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 'load_version' not in self._stubs: - self._stubs['load_version'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Versions/LoadVersion', - request_serializer=version.LoadVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['load_version'] - - -__all__ = ( - 'VersionsGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py deleted file mode 100644 index 4746a6d8..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py +++ /dev/null @@ -1,411 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import version -from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import VersionsTransport, DEFAULT_CLIENT_INFO -from .grpc import VersionsGrpcTransport - - -class VersionsGrpcAsyncIOTransport(VersionsTransport): - """gRPC AsyncIO backend transport for Versions. - - Service for managing - [Versions][google.cloud.dialogflow.cx.v3beta1.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] = {} - 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_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 in the specified - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. - - 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.cx.v3beta1.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 - [Version][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Versions/GetVersion', - request_serializer=version.GetVersionRequest.serialize, - response_deserializer=version.Version.deserialize, - ) - return self._stubs['get_version'] - - @property - def create_version(self) -> Callable[ - [gcdc_version.CreateVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create version method over gRPC. - - Creates a [Version][google.cloud.dialogflow.cx.v3beta1.Version] - in the specified - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. - - Returns: - Callable[[~.CreateVersionRequest], - 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_version' not in self._stubs: - self._stubs['create_version'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Versions/CreateVersion', - request_serializer=gcdc_version.CreateVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_version'] - - @property - def update_version(self) -> Callable[ - [gcdc_version.UpdateVersionRequest], - Awaitable[gcdc_version.Version]]: - r"""Return a callable for the update version method over gRPC. - - Updates the specified - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - - 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.cx.v3beta1.Versions/UpdateVersion', - request_serializer=gcdc_version.UpdateVersionRequest.serialize, - response_deserializer=gcdc_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. - - Deletes the specified - [Version][google.cloud.dialogflow.cx.v3beta1.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.cx.v3beta1.Versions/DeleteVersion', - request_serializer=version.DeleteVersionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_version'] - - @property - def load_version(self) -> Callable[ - [version.LoadVersionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the load version method over gRPC. - - Loads resources in the specified version to the draft - flow. - - Returns: - Callable[[~.LoadVersionRequest], - 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 'load_version' not in self._stubs: - self._stubs['load_version'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Versions/LoadVersion', - request_serializer=version.LoadVersionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['load_version'] - - -__all__ = ( - 'VersionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py deleted file mode 100644 index 8ace8262..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/__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 WebhooksClient -from .async_client import WebhooksAsyncClient - -__all__ = ( - 'WebhooksClient', - 'WebhooksAsyncClient', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py deleted file mode 100644 index 7521843b..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py +++ /dev/null @@ -1,581 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.webhooks import pagers -from google.cloud.dialogflowcx_v3beta1.types import webhook -from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport -from .client import WebhooksClient - - -class WebhooksAsyncClient: - """Service for managing - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook]. - """ - - _client: WebhooksClient - - DEFAULT_ENDPOINT = WebhooksClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = WebhooksClient.DEFAULT_MTLS_ENDPOINT - - service_path = staticmethod(WebhooksClient.service_path) - parse_service_path = staticmethod(WebhooksClient.parse_service_path) - webhook_path = staticmethod(WebhooksClient.webhook_path) - parse_webhook_path = staticmethod(WebhooksClient.parse_webhook_path) - common_billing_account_path = staticmethod(WebhooksClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(WebhooksClient.parse_common_billing_account_path) - common_folder_path = staticmethod(WebhooksClient.common_folder_path) - parse_common_folder_path = staticmethod(WebhooksClient.parse_common_folder_path) - common_organization_path = staticmethod(WebhooksClient.common_organization_path) - parse_common_organization_path = staticmethod(WebhooksClient.parse_common_organization_path) - common_project_path = staticmethod(WebhooksClient.common_project_path) - parse_common_project_path = staticmethod(WebhooksClient.parse_common_project_path) - common_location_path = staticmethod(WebhooksClient.common_location_path) - parse_common_location_path = staticmethod(WebhooksClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - 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: - WebhooksAsyncClient: The constructed client. - """ - return WebhooksClient.from_service_account_info.__func__(WebhooksAsyncClient, 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: - WebhooksAsyncClient: The constructed client. - """ - return WebhooksClient.from_service_account_file.__func__(WebhooksAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> WebhooksTransport: - """Returns the transport used by the client instance. - - Returns: - WebhooksTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(WebhooksClient).get_transport_class, type(WebhooksClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, WebhooksTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the webhooks 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, ~.WebhooksTransport]): 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 = WebhooksClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_webhooks(self, - request: webhook.ListWebhooksRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWebhooksAsyncPager: - r"""Returns the list of all webhooks in the specified - agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksRequest`): - The request object. The request message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. - parent (:class:`str`): - Required. The agent to list all webhooks for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.webhooks.pagers.ListWebhooksAsyncPager: - The response message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. - - 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 = webhook.ListWebhooksRequest(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_webhooks, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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.ListWebhooksAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_webhook(self, - request: webhook.GetWebhookRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> webhook.Webhook: - r"""Retrieves the specified webhook. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.GetWebhookRequest`): - The request object. The request message for - [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.GetWebhook]. - name (:class:`str`): - Required. The name of the webhook. Format: - ``projects//locations//agents//webhooks/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 = webhook.GetWebhookRequest(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_webhook, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided 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_webhook(self, - request: gcdc_webhook.CreateWebhookRequest = None, - *, - parent: str = None, - webhook: gcdc_webhook.Webhook = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_webhook.Webhook: - r"""Creates a webhook in the specified agent. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateWebhookRequest`): - The request object. The request message for - [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook]. - parent (:class:`str`): - Required. The agent to create a webhook for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - webhook (:class:`google.cloud.dialogflowcx_v3beta1.types.Webhook`): - Required. The webhook to create. - This corresponds to the ``webhook`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, webhook]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = gcdc_webhook.CreateWebhookRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if webhook is not None: - request.webhook = webhook - - # 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_webhook, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(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_webhook(self, - request: gcdc_webhook.UpdateWebhookRequest = None, - *, - webhook: gcdc_webhook.Webhook = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_webhook.Webhook: - r"""Updates the specified webhook. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.UpdateWebhookRequest`): - The request object. The request message for - [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook]. - webhook (:class:`google.cloud.dialogflowcx_v3beta1.types.Webhook`): - Required. The webhook to update. - This corresponds to the ``webhook`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - 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.dialogflowcx_v3beta1.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([webhook, 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 = gcdc_webhook.UpdateWebhookRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if webhook is not None: - request.webhook = webhook - if update_mask is not None: - 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_webhook, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("webhook.name", request.webhook.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_webhook(self, - request: webhook.DeleteWebhookRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified webhook. - - Args: - request (:class:`google.cloud.dialogflowcx_v3beta1.types.DeleteWebhookRequest`): - The request object. The request message for - [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.DeleteWebhook]. - name (:class:`str`): - Required. The name of the webhook to delete. Format: - ``projects//locations//agents//webhooks/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 = webhook.DeleteWebhookRequest(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_webhook, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "WebhooksAsyncClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py deleted file mode 100644 index 15bd73c4..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py +++ /dev/null @@ -1,777 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF 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.dialogflowcx_v3beta1.services.webhooks import pagers -from google.cloud.dialogflowcx_v3beta1.types import webhook -from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import WebhooksGrpcTransport -from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport - - -class WebhooksClientMeta(type): - """Metaclass for the Webhooks 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[WebhooksTransport]] - _transport_registry["grpc"] = WebhooksGrpcTransport - _transport_registry["grpc_asyncio"] = WebhooksGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[WebhooksTransport]: - """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 WebhooksClient(metaclass=WebhooksClientMeta): - """Service for managing - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook]. - """ - - @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: - WebhooksClient: 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: - WebhooksClient: 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) -> WebhooksTransport: - """Returns the transport used by the client instance. - - Returns: - WebhooksTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def service_path(project: str,location: str,namespace: str,service: str,) -> str: - """Returns a fully-qualified service string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - - @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: - """Parses a service path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def webhook_path(project: str,location: str,agent: str,webhook: str,) -> str: - """Returns a fully-qualified webhook string.""" - return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - - @staticmethod - def parse_webhook_path(path: str) -> Dict[str,str]: - """Parses a webhook path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?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, WebhooksTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the webhooks 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, WebhooksTransport]): 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, WebhooksTransport): - # transport is a WebhooksTransport 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_webhooks(self, - request: webhook.ListWebhooksRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListWebhooksPager: - r"""Returns the list of all webhooks in the specified - agent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksRequest): - The request object. The request message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. - parent (str): - Required. The agent to list all webhooks for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.services.webhooks.pagers.ListWebhooksPager: - The response message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. - - 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 webhook.ListWebhooksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, webhook.ListWebhooksRequest): - request = webhook.ListWebhooksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_webhooks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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.ListWebhooksPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_webhook(self, - request: webhook.GetWebhookRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> webhook.Webhook: - r"""Retrieves the specified webhook. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.GetWebhookRequest): - The request object. The request message for - [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.GetWebhook]. - name (str): - Required. The name of the webhook. Format: - ``projects//locations//agents//webhooks/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: 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 webhook.GetWebhookRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, webhook.GetWebhookRequest): - request = webhook.GetWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_webhook] - - # Certain fields should be provided 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_webhook(self, - request: gcdc_webhook.CreateWebhookRequest = None, - *, - parent: str = None, - webhook: gcdc_webhook.Webhook = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_webhook.Webhook: - r"""Creates a webhook in the specified agent. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.CreateWebhookRequest): - The request object. The request message for - [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook]. - parent (str): - Required. The agent to create a webhook for. Format: - ``projects//locations//agents/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - webhook (google.cloud.dialogflowcx_v3beta1.types.Webhook): - Required. The webhook to create. - This corresponds to the ``webhook`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflowcx_v3beta1.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, webhook]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a gcdc_webhook.CreateWebhookRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_webhook.CreateWebhookRequest): - request = gcdc_webhook.CreateWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if webhook is not None: - request.webhook = webhook - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_webhook] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = 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_webhook(self, - request: gcdc_webhook.UpdateWebhookRequest = None, - *, - webhook: gcdc_webhook.Webhook = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcdc_webhook.Webhook: - r"""Updates the specified webhook. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.UpdateWebhookRequest): - The request object. The request message for - [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook]. - webhook (google.cloud.dialogflowcx_v3beta1.types.Webhook): - Required. The webhook to update. - This corresponds to the ``webhook`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.dialogflowcx_v3beta1.types.Webhook: - Webhooks host the developer's - business logic. During a session, - webhooks allow the developer to use the - data extracted by Dialogflow's natural - language processing to generate dynamic - responses, validate collected data, or - trigger actions on the backend. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([webhook, 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 gcdc_webhook.UpdateWebhookRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, gcdc_webhook.UpdateWebhookRequest): - request = gcdc_webhook.UpdateWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if webhook is not None: - request.webhook = webhook - if update_mask is not None: - 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_webhook] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("webhook.name", request.webhook.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_webhook(self, - request: webhook.DeleteWebhookRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes the specified webhook. - - Args: - request (google.cloud.dialogflowcx_v3beta1.types.DeleteWebhookRequest): - The request object. The request message for - [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.DeleteWebhook]. - name (str): - Required. The name of the webhook to delete. Format: - ``projects//locations//agents//webhooks/``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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 webhook.DeleteWebhookRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, webhook.DeleteWebhookRequest): - request = webhook.DeleteWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_webhook] - - # Certain fields should be 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-dialogflowcx", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "WebhooksClient", -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py deleted file mode 100644 index 460d4218..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/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.dialogflowcx_v3beta1.types import webhook - - -class ListWebhooksPager: - """A pager for iterating through ``list_webhooks`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse` object, and - provides an ``__iter__`` method to iterate through its - ``webhooks`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWebhooks`` requests and continue to iterate - through the ``webhooks`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse` - 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[..., webhook.ListWebhooksResponse], - request: webhook.ListWebhooksRequest, - response: webhook.ListWebhooksResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse): - 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 = webhook.ListWebhooksRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[webhook.ListWebhooksResponse]: - 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[webhook.Webhook]: - for page in self.pages: - yield from page.webhooks - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWebhooksAsyncPager: - """A pager for iterating through ``list_webhooks`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``webhooks`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWebhooks`` requests and continue to iterate - through the ``webhooks`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse` - 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[webhook.ListWebhooksResponse]], - request: webhook.ListWebhooksRequest, - response: webhook.ListWebhooksResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksRequest): - The initial request object. - response (google.cloud.dialogflowcx_v3beta1.types.ListWebhooksResponse): - 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 = webhook.ListWebhooksRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[webhook.ListWebhooksResponse]: - 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[webhook.Webhook]: - async def async_generator(): - async for page in self.pages: - for response in page.webhooks: - 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/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py deleted file mode 100644 index 6006a6e7..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/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 WebhooksTransport -from .grpc import WebhooksGrpcTransport -from .grpc_asyncio import WebhooksGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[WebhooksTransport]] -_transport_registry['grpc'] = WebhooksGrpcTransport -_transport_registry['grpc_asyncio'] = WebhooksGrpcAsyncIOTransport - -__all__ = ( - 'WebhooksTransport', - 'WebhooksGrpcTransport', - 'WebhooksGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py deleted file mode 100644 index 7b811c5c..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/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.dialogflowcx_v3beta1.types import webhook -from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook -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-dialogflowcx', - ).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 WebhooksTransport(abc.ABC): - """Abstract transport class for Webhooks.""" - - 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_webhooks: gapic_v1.method.wrap_method( - self.list_webhooks, - default_timeout=None, - client_info=client_info, - ), - self.get_webhook: gapic_v1.method.wrap_method( - self.get_webhook, - default_timeout=None, - client_info=client_info, - ), - self.create_webhook: gapic_v1.method.wrap_method( - self.create_webhook, - default_timeout=None, - client_info=client_info, - ), - self.update_webhook: gapic_v1.method.wrap_method( - self.update_webhook, - default_timeout=None, - client_info=client_info, - ), - self.delete_webhook: gapic_v1.method.wrap_method( - self.delete_webhook, - default_timeout=None, - client_info=client_info, - ), - } - - @property - def list_webhooks(self) -> Callable[ - [webhook.ListWebhooksRequest], - Union[ - webhook.ListWebhooksResponse, - Awaitable[webhook.ListWebhooksResponse] - ]]: - raise NotImplementedError() - - @property - def get_webhook(self) -> Callable[ - [webhook.GetWebhookRequest], - Union[ - webhook.Webhook, - Awaitable[webhook.Webhook] - ]]: - raise NotImplementedError() - - @property - def create_webhook(self) -> Callable[ - [gcdc_webhook.CreateWebhookRequest], - Union[ - gcdc_webhook.Webhook, - Awaitable[gcdc_webhook.Webhook] - ]]: - raise NotImplementedError() - - @property - def update_webhook(self) -> Callable[ - [gcdc_webhook.UpdateWebhookRequest], - Union[ - gcdc_webhook.Webhook, - Awaitable[gcdc_webhook.Webhook] - ]]: - raise NotImplementedError() - - @property - def delete_webhook(self) -> Callable[ - [webhook.DeleteWebhookRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'WebhooksTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py deleted file mode 100644 index b860d115..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/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.dialogflowcx_v3beta1.types import webhook -from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook -from google.protobuf import empty_pb2 # type: ignore -from .base import WebhooksTransport, DEFAULT_CLIENT_INFO - - -class WebhooksGrpcTransport(WebhooksTransport): - """gRPC backend transport for Webhooks. - - Service for managing - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook]. - - 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_webhooks(self) -> Callable[ - [webhook.ListWebhooksRequest], - webhook.ListWebhooksResponse]: - r"""Return a callable for the list webhooks method over gRPC. - - Returns the list of all webhooks in the specified - agent. - - Returns: - Callable[[~.ListWebhooksRequest], - ~.ListWebhooksResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_webhooks' not in self._stubs: - self._stubs['list_webhooks'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Webhooks/ListWebhooks', - request_serializer=webhook.ListWebhooksRequest.serialize, - response_deserializer=webhook.ListWebhooksResponse.deserialize, - ) - return self._stubs['list_webhooks'] - - @property - def get_webhook(self) -> Callable[ - [webhook.GetWebhookRequest], - webhook.Webhook]: - r"""Return a callable for the get webhook method over gRPC. - - Retrieves the specified webhook. - - Returns: - Callable[[~.GetWebhookRequest], - ~.Webhook]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_webhook' not in self._stubs: - self._stubs['get_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Webhooks/GetWebhook', - request_serializer=webhook.GetWebhookRequest.serialize, - response_deserializer=webhook.Webhook.deserialize, - ) - return self._stubs['get_webhook'] - - @property - def create_webhook(self) -> Callable[ - [gcdc_webhook.CreateWebhookRequest], - gcdc_webhook.Webhook]: - r"""Return a callable for the create webhook method over gRPC. - - Creates a webhook in the specified agent. - - Returns: - Callable[[~.CreateWebhookRequest], - ~.Webhook]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_webhook' not in self._stubs: - self._stubs['create_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Webhooks/CreateWebhook', - request_serializer=gcdc_webhook.CreateWebhookRequest.serialize, - response_deserializer=gcdc_webhook.Webhook.deserialize, - ) - return self._stubs['create_webhook'] - - @property - def update_webhook(self) -> Callable[ - [gcdc_webhook.UpdateWebhookRequest], - gcdc_webhook.Webhook]: - r"""Return a callable for the update webhook method over gRPC. - - Updates the specified webhook. - - Returns: - Callable[[~.UpdateWebhookRequest], - ~.Webhook]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_webhook' not in self._stubs: - self._stubs['update_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Webhooks/UpdateWebhook', - request_serializer=gcdc_webhook.UpdateWebhookRequest.serialize, - response_deserializer=gcdc_webhook.Webhook.deserialize, - ) - return self._stubs['update_webhook'] - - @property - def delete_webhook(self) -> Callable[ - [webhook.DeleteWebhookRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete webhook method over gRPC. - - Deletes the specified webhook. - - Returns: - Callable[[~.DeleteWebhookRequest], - ~.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_webhook' not in self._stubs: - self._stubs['delete_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Webhooks/DeleteWebhook', - request_serializer=webhook.DeleteWebhookRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_webhook'] - - -__all__ = ( - 'WebhooksGrpcTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py deleted file mode 100644 index 5cfd1217..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/services/webhooks/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.dialogflowcx_v3beta1.types import webhook -from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook -from google.protobuf import empty_pb2 # type: ignore -from .base import WebhooksTransport, DEFAULT_CLIENT_INFO -from .grpc import WebhooksGrpcTransport - - -class WebhooksGrpcAsyncIOTransport(WebhooksTransport): - """gRPC AsyncIO backend transport for Webhooks. - - Service for managing - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook]. - - 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_webhooks(self) -> Callable[ - [webhook.ListWebhooksRequest], - Awaitable[webhook.ListWebhooksResponse]]: - r"""Return a callable for the list webhooks method over gRPC. - - Returns the list of all webhooks in the specified - agent. - - Returns: - Callable[[~.ListWebhooksRequest], - Awaitable[~.ListWebhooksResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_webhooks' not in self._stubs: - self._stubs['list_webhooks'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Webhooks/ListWebhooks', - request_serializer=webhook.ListWebhooksRequest.serialize, - response_deserializer=webhook.ListWebhooksResponse.deserialize, - ) - return self._stubs['list_webhooks'] - - @property - def get_webhook(self) -> Callable[ - [webhook.GetWebhookRequest], - Awaitable[webhook.Webhook]]: - r"""Return a callable for the get webhook method over gRPC. - - Retrieves the specified webhook. - - Returns: - Callable[[~.GetWebhookRequest], - Awaitable[~.Webhook]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_webhook' not in self._stubs: - self._stubs['get_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Webhooks/GetWebhook', - request_serializer=webhook.GetWebhookRequest.serialize, - response_deserializer=webhook.Webhook.deserialize, - ) - return self._stubs['get_webhook'] - - @property - def create_webhook(self) -> Callable[ - [gcdc_webhook.CreateWebhookRequest], - Awaitable[gcdc_webhook.Webhook]]: - r"""Return a callable for the create webhook method over gRPC. - - Creates a webhook in the specified agent. - - Returns: - Callable[[~.CreateWebhookRequest], - Awaitable[~.Webhook]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_webhook' not in self._stubs: - self._stubs['create_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Webhooks/CreateWebhook', - request_serializer=gcdc_webhook.CreateWebhookRequest.serialize, - response_deserializer=gcdc_webhook.Webhook.deserialize, - ) - return self._stubs['create_webhook'] - - @property - def update_webhook(self) -> Callable[ - [gcdc_webhook.UpdateWebhookRequest], - Awaitable[gcdc_webhook.Webhook]]: - r"""Return a callable for the update webhook method over gRPC. - - Updates the specified webhook. - - Returns: - Callable[[~.UpdateWebhookRequest], - Awaitable[~.Webhook]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_webhook' not in self._stubs: - self._stubs['update_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Webhooks/UpdateWebhook', - request_serializer=gcdc_webhook.UpdateWebhookRequest.serialize, - response_deserializer=gcdc_webhook.Webhook.deserialize, - ) - return self._stubs['update_webhook'] - - @property - def delete_webhook(self) -> Callable[ - [webhook.DeleteWebhookRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete webhook method over gRPC. - - Deletes the specified webhook. - - Returns: - Callable[[~.DeleteWebhookRequest], - 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_webhook' not in self._stubs: - self._stubs['delete_webhook'] = self.grpc_channel.unary_unary( - '/google.cloud.dialogflow.cx.v3beta1.Webhooks/DeleteWebhook', - request_serializer=webhook.DeleteWebhookRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_webhook'] - - -__all__ = ( - 'WebhooksGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/__init__.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/__init__.py deleted file mode 100644 index 6b900835..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/__init__.py +++ /dev/null @@ -1,430 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, - AgentValidationResult, - CreateAgentRequest, - DeleteAgentRequest, - ExportAgentRequest, - ExportAgentResponse, - GetAgentRequest, - GetAgentValidationResultRequest, - ListAgentsRequest, - ListAgentsResponse, - RestoreAgentRequest, - SpeechToTextSettings, - UpdateAgentRequest, - ValidateAgentRequest, -) -from .audio_config import ( - InputAudioConfig, - OutputAudioConfig, - SpeechWordInfo, - SynthesizeSpeechConfig, - VoiceSelectionParams, - AudioEncoding, - OutputAudioEncoding, - SpeechModelVariant, - SsmlVoiceGender, -) -from .entity_type import ( - CreateEntityTypeRequest, - DeleteEntityTypeRequest, - EntityType, - GetEntityTypeRequest, - ListEntityTypesRequest, - ListEntityTypesResponse, - UpdateEntityTypeRequest, -) -from .environment import ( - ContinuousTestResult, - CreateEnvironmentRequest, - DeleteEnvironmentRequest, - Environment, - GetEnvironmentRequest, - ListContinuousTestResultsRequest, - ListContinuousTestResultsResponse, - ListEnvironmentsRequest, - ListEnvironmentsResponse, - LookupEnvironmentHistoryRequest, - LookupEnvironmentHistoryResponse, - RunContinuousTestMetadata, - RunContinuousTestRequest, - RunContinuousTestResponse, - UpdateEnvironmentRequest, -) -from .experiment import ( - CreateExperimentRequest, - DeleteExperimentRequest, - Experiment, - GetExperimentRequest, - ListExperimentsRequest, - ListExperimentsResponse, - StartExperimentRequest, - StopExperimentRequest, - UpdateExperimentRequest, - VariantsHistory, - VersionVariants, -) -from .flow import ( - CreateFlowRequest, - DeleteFlowRequest, - ExportFlowRequest, - ExportFlowResponse, - Flow, - FlowValidationResult, - GetFlowRequest, - GetFlowValidationResultRequest, - ImportFlowRequest, - ImportFlowResponse, - ListFlowsRequest, - ListFlowsResponse, - NluSettings, - TrainFlowRequest, - UpdateFlowRequest, - ValidateFlowRequest, -) -from .fulfillment import ( - Fulfillment, -) -from .intent import ( - CreateIntentRequest, - DeleteIntentRequest, - GetIntentRequest, - Intent, - ListIntentsRequest, - ListIntentsResponse, - UpdateIntentRequest, - IntentView, -) -from .page import ( - CreatePageRequest, - DeletePageRequest, - EventHandler, - Form, - GetPageRequest, - ListPagesRequest, - ListPagesResponse, - Page, - TransitionRoute, - UpdatePageRequest, -) -from .response_message import ( - ResponseMessage, -) -from .security_settings import ( - CreateSecuritySettingsRequest, - DeleteSecuritySettingsRequest, - GetSecuritySettingsRequest, - ListSecuritySettingsRequest, - ListSecuritySettingsResponse, - SecuritySettings, - UpdateSecuritySettingsRequest, -) -from .session import ( - AudioInput, - DetectIntentRequest, - DetectIntentResponse, - DtmfInput, - EventInput, - FulfillIntentRequest, - FulfillIntentResponse, - IntentInput, - Match, - MatchIntentRequest, - MatchIntentResponse, - QueryInput, - QueryParameters, - QueryResult, - SentimentAnalysisResult, - StreamingDetectIntentRequest, - StreamingDetectIntentResponse, - StreamingRecognitionResult, - TextInput, -) -from .session_entity_type import ( - CreateSessionEntityTypeRequest, - DeleteSessionEntityTypeRequest, - GetSessionEntityTypeRequest, - ListSessionEntityTypesRequest, - ListSessionEntityTypesResponse, - SessionEntityType, - UpdateSessionEntityTypeRequest, -) -from .test_case import ( - BatchDeleteTestCasesRequest, - BatchRunTestCasesMetadata, - BatchRunTestCasesRequest, - BatchRunTestCasesResponse, - CalculateCoverageRequest, - CalculateCoverageResponse, - ConversationTurn, - CreateTestCaseRequest, - ExportTestCasesMetadata, - ExportTestCasesRequest, - ExportTestCasesResponse, - GetTestCaseRequest, - GetTestCaseResultRequest, - ImportTestCasesMetadata, - ImportTestCasesRequest, - ImportTestCasesResponse, - IntentCoverage, - ListTestCaseResultsRequest, - ListTestCaseResultsResponse, - ListTestCasesRequest, - ListTestCasesResponse, - RunTestCaseMetadata, - RunTestCaseRequest, - RunTestCaseResponse, - TestCase, - TestCaseError, - TestCaseResult, - TestConfig, - TestError, - TestRunDifference, - TransitionCoverage, - TransitionRouteGroupCoverage, - UpdateTestCaseRequest, - TestResult, -) -from .transition_route_group import ( - CreateTransitionRouteGroupRequest, - DeleteTransitionRouteGroupRequest, - GetTransitionRouteGroupRequest, - ListTransitionRouteGroupsRequest, - ListTransitionRouteGroupsResponse, - TransitionRouteGroup, - UpdateTransitionRouteGroupRequest, -) -from .validation_message import ( - ResourceName, - ValidationMessage, -) -from .version import ( - CreateVersionOperationMetadata, - CreateVersionRequest, - DeleteVersionRequest, - GetVersionRequest, - ListVersionsRequest, - ListVersionsResponse, - LoadVersionRequest, - UpdateVersionRequest, - Version, -) -from .webhook import ( - CreateWebhookRequest, - DeleteWebhookRequest, - GetWebhookRequest, - ListWebhooksRequest, - ListWebhooksResponse, - PageInfo, - SessionInfo, - UpdateWebhookRequest, - Webhook, - WebhookRequest, - WebhookResponse, -) - -__all__ = ( - 'Agent', - 'AgentValidationResult', - 'CreateAgentRequest', - 'DeleteAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'GetAgentRequest', - 'GetAgentValidationResultRequest', - 'ListAgentsRequest', - 'ListAgentsResponse', - 'RestoreAgentRequest', - 'SpeechToTextSettings', - 'UpdateAgentRequest', - 'ValidateAgentRequest', - 'InputAudioConfig', - 'OutputAudioConfig', - 'SpeechWordInfo', - 'SynthesizeSpeechConfig', - 'VoiceSelectionParams', - 'AudioEncoding', - 'OutputAudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'CreateEntityTypeRequest', - 'DeleteEntityTypeRequest', - 'EntityType', - 'GetEntityTypeRequest', - 'ListEntityTypesRequest', - 'ListEntityTypesResponse', - 'UpdateEntityTypeRequest', - 'ContinuousTestResult', - 'CreateEnvironmentRequest', - 'DeleteEnvironmentRequest', - 'Environment', - 'GetEnvironmentRequest', - 'ListContinuousTestResultsRequest', - 'ListContinuousTestResultsResponse', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LookupEnvironmentHistoryRequest', - 'LookupEnvironmentHistoryResponse', - 'RunContinuousTestMetadata', - 'RunContinuousTestRequest', - 'RunContinuousTestResponse', - 'UpdateEnvironmentRequest', - 'CreateExperimentRequest', - 'DeleteExperimentRequest', - 'Experiment', - 'GetExperimentRequest', - 'ListExperimentsRequest', - 'ListExperimentsResponse', - 'StartExperimentRequest', - 'StopExperimentRequest', - 'UpdateExperimentRequest', - 'VariantsHistory', - 'VersionVariants', - 'CreateFlowRequest', - 'DeleteFlowRequest', - 'ExportFlowRequest', - 'ExportFlowResponse', - 'Flow', - 'FlowValidationResult', - 'GetFlowRequest', - 'GetFlowValidationResultRequest', - 'ImportFlowRequest', - 'ImportFlowResponse', - 'ListFlowsRequest', - 'ListFlowsResponse', - 'NluSettings', - 'TrainFlowRequest', - 'UpdateFlowRequest', - 'ValidateFlowRequest', - 'Fulfillment', - 'CreateIntentRequest', - 'DeleteIntentRequest', - 'GetIntentRequest', - 'Intent', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'UpdateIntentRequest', - 'IntentView', - 'CreatePageRequest', - 'DeletePageRequest', - 'EventHandler', - 'Form', - 'GetPageRequest', - 'ListPagesRequest', - 'ListPagesResponse', - 'Page', - 'TransitionRoute', - 'UpdatePageRequest', - 'ResponseMessage', - 'CreateSecuritySettingsRequest', - 'DeleteSecuritySettingsRequest', - 'GetSecuritySettingsRequest', - 'ListSecuritySettingsRequest', - 'ListSecuritySettingsResponse', - 'SecuritySettings', - 'UpdateSecuritySettingsRequest', - 'AudioInput', - 'DetectIntentRequest', - 'DetectIntentResponse', - 'DtmfInput', - 'EventInput', - 'FulfillIntentRequest', - 'FulfillIntentResponse', - 'IntentInput', - 'Match', - 'MatchIntentRequest', - 'MatchIntentResponse', - 'QueryInput', - 'QueryParameters', - 'QueryResult', - 'SentimentAnalysisResult', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'TextInput', - 'CreateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - 'GetSessionEntityTypeRequest', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'SessionEntityType', - 'UpdateSessionEntityTypeRequest', - 'BatchDeleteTestCasesRequest', - 'BatchRunTestCasesMetadata', - 'BatchRunTestCasesRequest', - 'BatchRunTestCasesResponse', - 'CalculateCoverageRequest', - 'CalculateCoverageResponse', - 'ConversationTurn', - 'CreateTestCaseRequest', - 'ExportTestCasesMetadata', - 'ExportTestCasesRequest', - 'ExportTestCasesResponse', - 'GetTestCaseRequest', - 'GetTestCaseResultRequest', - 'ImportTestCasesMetadata', - 'ImportTestCasesRequest', - 'ImportTestCasesResponse', - 'IntentCoverage', - 'ListTestCaseResultsRequest', - 'ListTestCaseResultsResponse', - 'ListTestCasesRequest', - 'ListTestCasesResponse', - 'RunTestCaseMetadata', - 'RunTestCaseRequest', - 'RunTestCaseResponse', - 'TestCase', - 'TestCaseError', - 'TestCaseResult', - 'TestConfig', - 'TestError', - 'TestRunDifference', - 'TransitionCoverage', - 'TransitionRouteGroupCoverage', - 'UpdateTestCaseRequest', - 'TestResult', - 'CreateTransitionRouteGroupRequest', - 'DeleteTransitionRouteGroupRequest', - 'GetTransitionRouteGroupRequest', - 'ListTransitionRouteGroupsRequest', - 'ListTransitionRouteGroupsResponse', - 'TransitionRouteGroup', - 'UpdateTransitionRouteGroupRequest', - 'ResourceName', - 'ValidationMessage', - 'CreateVersionOperationMetadata', - 'CreateVersionRequest', - 'DeleteVersionRequest', - 'GetVersionRequest', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'LoadVersionRequest', - 'UpdateVersionRequest', - 'Version', - 'CreateWebhookRequest', - 'DeleteWebhookRequest', - 'GetWebhookRequest', - 'ListWebhooksRequest', - 'ListWebhooksResponse', - 'PageInfo', - 'SessionInfo', - 'UpdateWebhookRequest', - 'Webhook', - 'WebhookRequest', - 'WebhookResponse', -) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/agent.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/agent.py deleted file mode 100644 index 5488e1a8..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/agent.py +++ /dev/null @@ -1,491 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import flow -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'SpeechToTextSettings', - 'Agent', - 'ListAgentsRequest', - 'ListAgentsResponse', - 'GetAgentRequest', - 'CreateAgentRequest', - 'UpdateAgentRequest', - 'DeleteAgentRequest', - 'ExportAgentRequest', - 'ExportAgentResponse', - 'RestoreAgentRequest', - 'ValidateAgentRequest', - 'GetAgentValidationResultRequest', - 'AgentValidationResult', - }, -) - - -class SpeechToTextSettings(proto.Message): - r"""Settings related to speech recognition. - Attributes: - enable_speech_adaptation (bool): - Whether to use speech adaptation for speech - recognition. - """ - - enable_speech_adaptation = proto.Field( - proto.BOOL, - number=1, - ) - - -class Agent(proto.Message): - r"""Agents are best described as Natural Language Understanding (NLU) - modules that transform user requests into actionable data. You can - include agents in your app, product, or service to determine user - intent and respond to the user in a natural way. - - After you create an agent, you can add - [Intents][google.cloud.dialogflow.cx.v3beta1.Intent], [Entity - Types][google.cloud.dialogflow.cx.v3beta1.EntityType], - [Flows][google.cloud.dialogflow.cx.v3beta1.Flow], - [Fulfillments][google.cloud.dialogflow.cx.v3beta1.Fulfillment], - [Webhooks][google.cloud.dialogflow.cx.v3beta1.Webhook], and so on to - manage the conversation flows.. - - Attributes: - name (str): - The unique identifier of the agent. Required for the - [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent] - method. - [Agents.CreateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.CreateAgent] - populates the name automatically. Format: - ``projects//locations//agents/``. - display_name (str): - Required. The human-readable name of the - agent, unique within the location. - default_language_code (str): - Immutable. 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 - [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent] - method. - supported_language_codes (Sequence[str]): - The list of all languages supported by the agent (except for - the ``default_language_code``). - time_zone (str): - Required. The time zone of the agent from the `time zone - database `__, e.g., - America/New_York, Europe/Paris. - description (str): - The description of the agent. The maximum - length is 500 characters. If exceeded, the - request is rejected. - avatar_uri (str): - The URI of the agent's avatar. Avatars are used throughout - the Dialogflow console and in the self-hosted `Web - Demo `__ - integration. - speech_to_text_settings (google.cloud.dialogflowcx_v3beta1.types.SpeechToTextSettings): - Speech recognition related settings. - start_flow (str): - Immutable. Name of the start flow in this agent. A start - flow will be automatically created when the agent is - created, and can only be deleted by deleting the agent. - Format: - ``projects//locations//agents//flows/``. - security_settings (str): - Name of the - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] - reference for the agent. Format: - ``projects//locations//securitySettings/``. - enable_stackdriver_logging (bool): - Indicates if stackdriver logging is enabled - for the agent. - enable_spell_correction (bool): - Indicates if automatic spell correction is - enabled in detect intent requests. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - default_language_code = proto.Field( - proto.STRING, - number=3, - ) - supported_language_codes = proto.RepeatedField( - proto.STRING, - number=4, - ) - time_zone = proto.Field( - proto.STRING, - number=5, - ) - description = proto.Field( - proto.STRING, - number=6, - ) - avatar_uri = proto.Field( - proto.STRING, - number=7, - ) - speech_to_text_settings = proto.Field( - proto.MESSAGE, - number=13, - message='SpeechToTextSettings', - ) - start_flow = proto.Field( - proto.STRING, - number=16, - ) - security_settings = proto.Field( - proto.STRING, - number=17, - ) - enable_stackdriver_logging = proto.Field( - proto.BOOL, - number=18, - ) - enable_spell_correction = proto.Field( - proto.BOOL, - number=20, - ) - - -class ListAgentsRequest(proto.Message): - r"""The request message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. - - Attributes: - parent (str): - Required. The location to list all agents for. 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 ListAgentsResponse(proto.Message): - r"""The response message for - [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents]. - - Attributes: - agents (Sequence[google.cloud.dialogflowcx_v3beta1.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 GetAgentRequest(proto.Message): - r"""The request message for - [Agents.GetAgent][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgent]. - - Attributes: - name (str): - Required. The name of the agent. Format: - ``projects//locations//agents/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateAgentRequest(proto.Message): - r"""The request message for - [Agents.CreateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.CreateAgent]. - - Attributes: - parent (str): - Required. The location to create a agent for. Format: - ``projects//locations/``. - agent (google.cloud.dialogflowcx_v3beta1.types.Agent): - Required. The agent to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - agent = proto.Field( - proto.MESSAGE, - number=2, - message='Agent', - ) - - -class UpdateAgentRequest(proto.Message): - r"""The request message for - [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent]. - - Attributes: - agent (google.cloud.dialogflowcx_v3beta1.types.Agent): - Required. The agent to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The mask to control which fields get updated. - If the mask is not present, all fields will be - 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.cx.v3beta1.Agents.DeleteAgent]. - - Attributes: - name (str): - Required. The name of the agent to delete. Format: - ``projects//locations//agents/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ExportAgentRequest(proto.Message): - r"""The request message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ExportAgent]. - - Attributes: - name (str): - Required. The name of the agent to export. Format: - ``projects//locations//agents/``. - 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. - environment (str): - Optional. Environment name. If not set, draft environment is - assumed. Format: - ``projects//locations//agents//environments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - agent_uri = proto.Field( - proto.STRING, - number=2, - ) - environment = proto.Field( - proto.STRING, - number=5, - ) - - -class ExportAgentResponse(proto.Message): - r"""The response message for - [Agents.ExportAgent][google.cloud.dialogflow.cx.v3beta1.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][google.cloud.dialogflow.cx.v3beta1.ExportAgentRequest]. - agent_content (bytes): - Uncompressed raw byte content for agent. - """ - - agent_uri = proto.Field( - proto.STRING, - number=1, - oneof='agent', - ) - agent_content = proto.Field( - proto.BYTES, - number=2, - oneof='agent', - ) - - -class RestoreAgentRequest(proto.Message): - r"""The request message for - [Agents.RestoreAgent][google.cloud.dialogflow.cx.v3beta1.Agents.RestoreAgent]. - - Attributes: - name (str): - Required. The name of the agent to restore into. Format: - ``projects//locations//agents/``. - agent_uri (str): - The `Google Cloud - Storage `__ URI to - restore agent from. The format of this URI must be - ``gs:///``. - agent_content (bytes): - Uncompressed raw byte content for agent. - restore_option (google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest.RestoreOption): - Agent restore mode. If not specified, ``KEEP`` is assumed. - """ - class RestoreOption(proto.Enum): - r"""Restore option.""" - RESTORE_OPTION_UNSPECIFIED = 0 - KEEP = 1 - FALLBACK = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - agent_uri = proto.Field( - proto.STRING, - number=2, - oneof='agent', - ) - agent_content = proto.Field( - proto.BYTES, - number=3, - oneof='agent', - ) - restore_option = proto.Field( - proto.ENUM, - number=5, - enum=RestoreOption, - ) - - -class ValidateAgentRequest(proto.Message): - r"""The request message for - [Agents.ValidateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.ValidateAgent]. - - Attributes: - name (str): - Required. The agent to validate. Format: - ``projects//locations//agents/``. - language_code (str): - If not specified, the agent's default - language is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class GetAgentValidationResultRequest(proto.Message): - r"""The request message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. - - Attributes: - name (str): - Required. The agent name. Format: - ``projects//locations//agents//validationResult``. - language_code (str): - If not specified, the agent's default - language is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class AgentValidationResult(proto.Message): - r"""The response message for - [Agents.GetAgentValidationResult][google.cloud.dialogflow.cx.v3beta1.Agents.GetAgentValidationResult]. - - Attributes: - name (str): - The unique identifier of the agent validation result. - Format: - ``projects//locations//agents//validationResult``. - flow_validation_results (Sequence[google.cloud.dialogflowcx_v3beta1.types.FlowValidationResult]): - Contains all flow validation results. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - flow_validation_results = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=flow.FlowValidationResult, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/audio_config.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/audio_config.py deleted file mode 100644 index e7611ee0..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/audio_config.py +++ /dev/null @@ -1,357 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cx.v3beta1', - manifest={ - 'AudioEncoding', - 'SpeechModelVariant', - 'SsmlVoiceGender', - 'OutputAudioEncoding', - 'SpeechWordInfo', - 'InputAudioConfig', - 'VoiceSelectionParams', - 'SynthesizeSpeechConfig', - 'OutputAudioConfig', - }, -) - - -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.cx.v3beta1.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 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.dialogflowcx_v3beta1.types.AudioEncoding): - Required. Audio encoding of the audio content - to process. - sample_rate_hertz (int): - Sample rate (in Hertz) of the audio content sent in the - query. Refer to `Cloud Speech API - documentation `__ - for more details. - enable_word_info (bool): - Optional. If ``true``, Dialogflow returns - [SpeechWordInfo][google.cloud.dialogflow.cx.v3beta1.SpeechWordInfo] - in - [StreamingRecognitionResult][google.cloud.dialogflow.cx.v3beta1.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]): - Optional. 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. - model (str): - Optional. 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.dialogflowcx_v3beta1.types.SpeechModelVariant): - Optional. Which variant of the [Speech - model][google.cloud.dialogflow.cx.v3beta1.InputAudioConfig.model] - to use. - single_utterance (bool): - Optional. 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. - """ - - audio_encoding = proto.Field( - proto.ENUM, - number=1, - enum='AudioEncoding', - ) - sample_rate_hertz = proto.Field( - proto.INT32, - number=2, - ) - enable_word_info = proto.Field( - proto.BOOL, - number=13, - ) - phrase_hints = proto.RepeatedField( - proto.STRING, - number=4, - ) - model = proto.Field( - proto.STRING, - number=7, - ) - model_variant = proto.Field( - proto.ENUM, - number=10, - enum='SpeechModelVariant', - ) - single_utterance = proto.Field( - proto.BOOL, - number=8, - ) - - -class VoiceSelectionParams(proto.Message): - r"""Description of which voice to use for speech synthesis. - Attributes: - name (str): - Optional. The name of the voice. If not set, the service - will choose a voice based on the other parameters such as - language_code and - [ssml_gender][google.cloud.dialogflow.cx.v3beta1.VoiceSelectionParams.ssml_gender]. - - For the list of available voices, please refer to `Supported - voices and - languages `__. - ssml_gender (google.cloud.dialogflowcx_v3beta1.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.cx.v3beta1.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.dialogflowcx_v3beta1.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. - - Attributes: - audio_encoding (google.cloud.dialogflowcx_v3beta1.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_config (google.cloud.dialogflowcx_v3beta1.types.SynthesizeSpeechConfig): - Optional. 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', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/entity_type.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/entity_type.py deleted file mode 100644 index 6ad3443d..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/entity_type.py +++ /dev/null @@ -1,425 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cx.v3beta1', - manifest={ - 'EntityType', - 'ListEntityTypesRequest', - 'ListEntityTypesResponse', - 'GetEntityTypeRequest', - 'CreateEntityTypeRequest', - 'UpdateEntityTypeRequest', - 'DeleteEntityTypeRequest', - }, -) - - -class EntityType(proto.Message): - r"""Entities are extracted from user input and represent parameters that - are meaningful to your application. For example, a date range, a - proper name such as a geographic location or landmark, and so on. - Entities represent actionable data for your application. - - When you define an entity, you can also include synonyms that all - map to that entity. For example, "soft drink", "soda", "pop", and so - on. - - There are three types of entities: - - - **System** - entities that are defined by the Dialogflow API for - common data types such as date, time, currency, and so on. A - system entity is represented by the ``EntityType`` type. - - - **Custom** - entities that are defined by you that represent - actionable data that is meaningful to your application. For - example, you could define a ``pizza.sauce`` entity for red or - white pizza sauce, a ``pizza.cheese`` entity for the different - types of cheese on a pizza, a ``pizza.topping`` entity for - different toppings, and so on. A custom entity is represented by - the ``EntityType`` type. - - - **User** - entities that are built for an individual user such as - favorites, preferences, playlists, and so on. A user entity is - represented by the - [SessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityType] - type. - - For more information about entity types, see the `Dialogflow - documentation `__. - - Attributes: - name (str): - The unique identifier of the entity type. Required for - [EntityTypes.UpdateEntityType][google.cloud.dialogflow.cx.v3beta1.EntityTypes.UpdateEntityType]. - Format: - ``projects//locations//agents//entityTypes/``. - display_name (str): - Required. The human-readable name of the - entity type, unique within the agent. - kind (google.cloud.dialogflowcx_v3beta1.types.EntityType.Kind): - Required. Indicates the kind of entity type. - auto_expansion_mode (google.cloud.dialogflowcx_v3beta1.types.EntityType.AutoExpansionMode): - Indicates whether the entity type can be - automatically expanded. - entities (Sequence[google.cloud.dialogflowcx_v3beta1.types.EntityType.Entity]): - The collection of entity entries associated - with the entity type. - excluded_phrases (Sequence[google.cloud.dialogflowcx_v3beta1.types.EntityType.ExcludedPhrase]): - Collection of exceptional words and phrases that shouldn't - be matched. For example, if you have a size entity type with - entry ``giant``\ (an adjective), you might consider adding - ``giants``\ (a noun) as an exclusion. If the kind of entity - type is ``KIND_MAP``, then the phrases specified by entities - and excluded phrases should be mutually exclusive. - enable_fuzzy_extraction (bool): - Enables fuzzy entity extraction during - classification. - redact (bool): - Indicates whether parameters of the entity - type should be redacted in log. If redaction is - enabled, page parameters and intent parameters - referring to the entity type will be replaced by - parameter name during logging. - """ - 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 canonical 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, - ) - - class ExcludedPhrase(proto.Message): - r"""An excluded entity phrase that should not be matched. - Attributes: - value (str): - Required. The word or phrase to be excluded. - """ - - value = proto.Field( - proto.STRING, - number=1, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - kind = proto.Field( - proto.ENUM, - number=3, - enum=Kind, - ) - auto_expansion_mode = proto.Field( - proto.ENUM, - number=4, - enum=AutoExpansionMode, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Entity, - ) - excluded_phrases = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=ExcludedPhrase, - ) - enable_fuzzy_extraction = proto.Field( - proto.BOOL, - number=7, - ) - redact = proto.Field( - proto.BOOL, - number=9, - ) - - -class ListEntityTypesRequest(proto.Message): - r"""The request message for - [EntityTypes.ListEntityTypes][google.cloud.dialogflow.cx.v3beta1.EntityTypes.ListEntityTypes]. - - Attributes: - parent (str): - Required. The agent to list all entity types for. Format: - ``projects//locations//agents/``. - language_code (str): - The language to list entity types for. The following fields - are language dependent: - - - ``EntityType.entities.value`` - - ``EntityType.entities.synonyms`` - - ``EntityType.excluded_phrases.value`` - - 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. - 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, - ) - 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.cx.v3beta1.EntityTypes.ListEntityTypes]. - - Attributes: - entity_types (Sequence[google.cloud.dialogflowcx_v3beta1.types.EntityType]): - The list of 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.cx.v3beta1.EntityTypes.GetEntityType]. - - Attributes: - name (str): - Required. The name of the entity type. Format: - ``projects//locations//agents//entityTypes/``. - language_code (str): - The language to retrieve the entity type for. The following - fields are language dependent: - - - ``EntityType.entities.value`` - - ``EntityType.entities.synonyms`` - - ``EntityType.excluded_phrases.value`` - - 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. - """ - - 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.cx.v3beta1.EntityTypes.CreateEntityType]. - - Attributes: - parent (str): - Required. The agent to create a entity type for. Format: - ``projects//locations//agents/``. - entity_type (google.cloud.dialogflowcx_v3beta1.types.EntityType): - Required. The entity type to create. - language_code (str): - The language of the following fields in ``entity_type``: - - - ``EntityType.entities.value`` - - ``EntityType.entities.synonyms`` - - ``EntityType.excluded_phrases.value`` - - 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, - ) - 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.cx.v3beta1.EntityTypes.UpdateEntityType]. - - Attributes: - entity_type (google.cloud.dialogflowcx_v3beta1.types.EntityType): - Required. The entity type to update. - language_code (str): - The language of the following fields in ``entity_type``: - - - ``EntityType.entities.value`` - - ``EntityType.entities.synonyms`` - - ``EntityType.excluded_phrases.value`` - - 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. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.cx.v3beta1.EntityTypes.DeleteEntityType]. - - Attributes: - name (str): - Required. The name of the entity type to delete. Format: - ``projects//locations//agents//entityTypes/``. - force (bool): - This field has no effect for entity type not being used. For - entity types that are used by intents or pages: - - - If ``force`` is set to false, an error will be returned - with message indicating the referencing resources. - - If ``force`` is set to true, Dialogflow will remove the - entity type, as well as any references to the entity type - (i.e. Page - [parameter][google.cloud.dialogflow.cx.v3beta1.Form.Parameter] - of the entity type will be changed to '@sys.any' and - intent - [parameter][google.cloud.dialogflow.cx.v3beta1.Intent.Parameter] - of the entity type will be removed). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/environment.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/environment.py deleted file mode 100644 index 57ea3cce..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/environment.py +++ /dev/null @@ -1,478 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import test_case -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'Environment', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'GetEnvironmentRequest', - 'CreateEnvironmentRequest', - 'UpdateEnvironmentRequest', - 'DeleteEnvironmentRequest', - 'LookupEnvironmentHistoryRequest', - 'LookupEnvironmentHistoryResponse', - 'ContinuousTestResult', - 'RunContinuousTestRequest', - 'RunContinuousTestResponse', - 'RunContinuousTestMetadata', - 'ListContinuousTestResultsRequest', - 'ListContinuousTestResultsResponse', - }, -) - - -class Environment(proto.Message): - r"""Represents an environment for an agent. 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. - - Attributes: - name (str): - The name of the environment. Format: - ``projects//locations//agents//environments/``. - display_name (str): - Required. The human-readable name of the - environment (unique in an agent). Limit of 64 - characters. - description (str): - The human-readable description of the - environment. The maximum length is 500 - characters. If exceeded, the request is - rejected. - version_configs (Sequence[google.cloud.dialogflowcx_v3beta1.types.Environment.VersionConfig]): - Required. A list of configurations for flow versions. You - should include version configs for all flows that are - reachable from [``Start Flow``][Agent.start_flow] in the - agent. Otherwise, an error will be returned. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Update time of this environment. - """ - - class VersionConfig(proto.Message): - r"""Configuration for the version. - Attributes: - version (str): - Required. Format: projects//locations//agents//flows//versions/. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - version_configs = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=VersionConfig, - ) - update_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -class ListEnvironmentsRequest(proto.Message): - r"""The request message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.Environments.ListEnvironments]. - - Attributes: - parent (str): - Required. The - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to list - all environments for. Format: - ``projects//locations//agents/``. - page_size (int): - The maximum number of items to return in a - single page. By default 20 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 ListEnvironmentsResponse(proto.Message): - r"""The response message for - [Environments.ListEnvironments][google.cloud.dialogflow.cx.v3beta1.Environments.ListEnvironments]. - - Attributes: - environments (Sequence[google.cloud.dialogflowcx_v3beta1.types.Environment]): - The list of environments. There will be a maximum number of - items returned based on the page_size field in the request. - The list may in some cases be empty or contain fewer entries - than page_size even if this isn't the last page. - 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.cx.v3beta1.Environments.GetEnvironment]. - - Attributes: - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - Format: - ``projects//locations//agents//environments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.CreateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.CreateEnvironment]. - - Attributes: - parent (str): - Required. The - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to create - an - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - for. Format: - ``projects//locations//agents/``. - environment (google.cloud.dialogflowcx_v3beta1.types.Environment): - Required. The environment to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - environment = proto.Field( - proto.MESSAGE, - number=2, - message='Environment', - ) - - -class UpdateEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.UpdateEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.UpdateEnvironment]. - - Attributes: - environment (google.cloud.dialogflowcx_v3beta1.types.Environment): - Required. The environment to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields - get updated. - """ - - environment = proto.Field( - proto.MESSAGE, - number=1, - message='Environment', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteEnvironmentRequest(proto.Message): - r"""The request message for - [Environments.DeleteEnvironment][google.cloud.dialogflow.cx.v3beta1.Environments.DeleteEnvironment]. - - Attributes: - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - to delete. Format: - ``projects//locations//agents//environments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class LookupEnvironmentHistoryRequest(proto.Message): - r"""The request message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. - - Attributes: - name (str): - Required. Resource name of the environment to look up the - history for. Format: - ``projects//locations//agents//environments/``. - 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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class LookupEnvironmentHistoryResponse(proto.Message): - r"""The response message for - [Environments.LookupEnvironmentHistory][google.cloud.dialogflow.cx.v3beta1.Environments.LookupEnvironmentHistory]. - - Attributes: - environments (Sequence[google.cloud.dialogflowcx_v3beta1.types.Environment]): - Represents a list of snapshots for an environment. Time of - the snapshots is stored in - [``update_time``][google.cloud.dialogflow.cx.v3beta1.Environment.update_time]. - 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 ContinuousTestResult(proto.Message): - r"""Represents a result from running a test case in an agent - environment. - - Attributes: - name (str): - The resource name for the continuous test result. Format: - ``projects//locations//agents//environments//continuousTestResults/``. - result (google.cloud.dialogflowcx_v3beta1.types.ContinuousTestResult.AggregatedTestResult): - The result of this continuous test run, i.e. - whether all the tests in this continuous test - run pass or not. - test_case_results (Sequence[str]): - A list of individual test case results names - in this continuous test run. - run_time (google.protobuf.timestamp_pb2.Timestamp): - Time when the continuous testing run starts. - """ - class AggregatedTestResult(proto.Enum): - r"""The overall result for a continuous test run in an agent - environment. - """ - AGGREGATED_TEST_RESULT_UNSPECIFIED = 0 - PASSED = 1 - FAILED = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - result = proto.Field( - proto.ENUM, - number=2, - enum=AggregatedTestResult, - ) - test_case_results = proto.RepeatedField( - proto.STRING, - number=3, - ) - run_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -class RunContinuousTestRequest(proto.Message): - r"""The request message for - [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. - - Attributes: - environment (str): - Required. Format: - ``projects//locations//agents//environments/``. - """ - - environment = proto.Field( - proto.STRING, - number=1, - ) - - -class RunContinuousTestResponse(proto.Message): - r"""The response message for - [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest]. - - Attributes: - continuous_test_result (google.cloud.dialogflowcx_v3beta1.types.ContinuousTestResult): - The result for a continuous test run. - """ - - continuous_test_result = proto.Field( - proto.MESSAGE, - number=1, - message='ContinuousTestResult', - ) - - -class RunContinuousTestMetadata(proto.Message): - r"""Metadata returned for the - [Environments.RunContinuousTest][google.cloud.dialogflow.cx.v3beta1.Environments.RunContinuousTest] - long running operation. - - Attributes: - errors (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestError]): - The test errors. - """ - - errors = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=test_case.TestError, - ) - - -class ListContinuousTestResultsRequest(proto.Message): - r"""The request message for - [Environments.ListContinuousTestResults][google.cloud.dialogflow.cx.v3beta1.Environments.ListContinuousTestResults]. - - Attributes: - parent (str): - Required. The environment to list results for. Format: - ``projects//locations//agents// environments/``. - 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 ListContinuousTestResultsResponse(proto.Message): - r"""The response message for [Environments.ListTestCaseResults][]. - Attributes: - continuous_test_results (Sequence[google.cloud.dialogflowcx_v3beta1.types.ContinuousTestResult]): - The list of continuous test results. - 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 - - continuous_test_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ContinuousTestResult', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/experiment.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/experiment.py deleted file mode 100644 index 0cb3bbd1..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/experiment.py +++ /dev/null @@ -1,570 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'Experiment', - 'VersionVariants', - 'VariantsHistory', - 'ListExperimentsRequest', - 'ListExperimentsResponse', - 'GetExperimentRequest', - 'CreateExperimentRequest', - 'UpdateExperimentRequest', - 'DeleteExperimentRequest', - 'StartExperimentRequest', - 'StopExperimentRequest', - }, -) - - -class Experiment(proto.Message): - r"""Represents an experiment in an environment. - Attributes: - name (str): - The name of the experiment. - Format: projects//locations//agents//environments//experiments/.. - display_name (str): - Required. The human-readable name of the - experiment (unique in an environment). Limit of - 64 characters. - description (str): - The human-readable description of the - experiment. - state (google.cloud.dialogflowcx_v3beta1.types.Experiment.State): - The current state of the experiment. - Transition triggered by - Expriments.StartExperiment: PENDING->RUNNING. - Transition triggered by - Expriments.CancelExperiment: PENDING->CANCELLED - or RUNNING->CANCELLED. - definition (google.cloud.dialogflowcx_v3beta1.types.Experiment.Definition): - The definition of the experiment. - result (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result): - Inference result of the experiment. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Creation time of this experiment. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start time of this experiment. - end_time (google.protobuf.timestamp_pb2.Timestamp): - End time of this experiment. - last_update_time (google.protobuf.timestamp_pb2.Timestamp): - Last update time of this experiment. - experiment_length (google.protobuf.duration_pb2.Duration): - Maximum number of days to run the experiment. - If auto-rollout is not enabled, default value - and maximum will be 30 days. If auto-rollout is - enabled, default value and maximum will be 6 - days. - variants_history (Sequence[google.cloud.dialogflowcx_v3beta1.types.VariantsHistory]): - The history of updates to the experiment - variants. - """ - class State(proto.Enum): - r"""The state of the experiment.""" - STATE_UNSPECIFIED = 0 - DRAFT = 1 - RUNNING = 2 - DONE = 3 - - class Definition(proto.Message): - r"""Definition of the experiment. - Attributes: - condition (str): - The condition defines which subset of sessions are selected - for this experiment. If not specified, all sessions are - eligible. E.g. "query_input.language_code=en" See the - `conditions - reference `__. - version_variants (google.cloud.dialogflowcx_v3beta1.types.VersionVariants): - The flow versions as the variants of this - experiment. - """ - - condition = proto.Field( - proto.STRING, - number=1, - ) - version_variants = proto.Field( - proto.MESSAGE, - number=2, - oneof='variants', - message='VersionVariants', - ) - - class Result(proto.Message): - r"""The inference result which includes an objective metric to - optimize and the confidence interval. - - Attributes: - version_metrics (Sequence[google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.VersionMetrics]): - Version variants and metrics. - last_update_time (google.protobuf.timestamp_pb2.Timestamp): - The last time the experiment's stats data was - updated. Will have default value if stats have - never been computed for this experiment. - """ - class MetricType(proto.Enum): - r"""Types of ratio-based metric for Dialogflow experiment.""" - METRIC_UNSPECIFIED = 0 - CONTAINED_SESSION_NO_CALLBACK_RATE = 1 - LIVE_AGENT_HANDOFF_RATE = 2 - CALLBACK_SESSION_RATE = 3 - ABANDONED_SESSION_RATE = 4 - SESSION_END_RATE = 5 - - class CountType(proto.Enum): - r"""types of count-based metric for Dialogflow experiment.""" - COUNT_TYPE_UNSPECIFIED = 0 - TOTAL_NO_MATCH_COUNT = 1 - TOTAL_TURN_COUNT = 2 - AVERAGE_TURN_COUNT = 3 - - class ConfidenceInterval(proto.Message): - r"""A confidence interval is a range of possible values for the - experiment objective you are trying to measure. - - Attributes: - confidence_level (float): - The confidence level used to construct the - interval, i.e. there is X% chance that the true - value is within this interval. - ratio (float): - The percent change between an experiment - metric's value and the value for its control. - lower_bound (float): - Lower bound of the interval. - upper_bound (float): - Upper bound of the interval. - """ - - confidence_level = proto.Field( - proto.DOUBLE, - number=1, - ) - ratio = proto.Field( - proto.DOUBLE, - number=2, - ) - lower_bound = proto.Field( - proto.DOUBLE, - number=3, - ) - upper_bound = proto.Field( - proto.DOUBLE, - number=4, - ) - - class Metric(proto.Message): - r"""Metric and corresponding confidence intervals. - Attributes: - type_ (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.MetricType): - Ratio-based metric type. Only one of type or count_type is - specified in each Metric. - count_type (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.CountType): - Count-based metric type. Only one of type or count_type is - specified in each Metric. - ratio (float): - Ratio value of a metric. - count (float): - Count value of a metric. - confidence_interval (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.ConfidenceInterval): - The probability that the treatment is better - than all other treatments in the experiment - """ - - type_ = proto.Field( - proto.ENUM, - number=1, - enum='Experiment.Result.MetricType', - ) - count_type = proto.Field( - proto.ENUM, - number=5, - enum='Experiment.Result.CountType', - ) - ratio = proto.Field( - proto.DOUBLE, - number=2, - oneof='value', - ) - count = proto.Field( - proto.DOUBLE, - number=4, - oneof='value', - ) - confidence_interval = proto.Field( - proto.MESSAGE, - number=3, - message='Experiment.Result.ConfidenceInterval', - ) - - class VersionMetrics(proto.Message): - r"""Version variant and associated metrics. - Attributes: - version (str): - The name of the flow - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - Format: - ``projects//locations//agents//flows//versions/``. - metrics (Sequence[google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.Metric]): - The metrics and corresponding confidence - intervals in the inference result. - session_count (int): - Number of sessions that were allocated to - this version. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - metrics = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Experiment.Result.Metric', - ) - session_count = proto.Field( - proto.INT32, - number=3, - ) - - version_metrics = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Experiment.Result.VersionMetrics', - ) - last_update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - state = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - definition = proto.Field( - proto.MESSAGE, - number=5, - message=Definition, - ) - result = proto.Field( - proto.MESSAGE, - number=6, - message=Result, - ) - create_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - start_time = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - end_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - last_update_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - experiment_length = proto.Field( - proto.MESSAGE, - number=11, - message=duration_pb2.Duration, - ) - variants_history = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='VariantsHistory', - ) - - -class VersionVariants(proto.Message): - r"""A list of flow version variants. - Attributes: - variants (Sequence[google.cloud.dialogflowcx_v3beta1.types.VersionVariants.Variant]): - A list of flow version variants. - """ - - class Variant(proto.Message): - r"""A single flow version with specified traffic allocation. - Attributes: - version (str): - The name of the flow version. Format: - ``projects//locations//agents//flows//versions/``. - traffic_allocation (float): - Percentage of the traffic which should be - routed to this version of flow. Traffic - allocation for a single flow must sum up to 1.0. - is_control_group (bool): - Whether the variant is for the control group. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - traffic_allocation = proto.Field( - proto.FLOAT, - number=2, - ) - is_control_group = proto.Field( - proto.BOOL, - number=3, - ) - - variants = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Variant, - ) - - -class VariantsHistory(proto.Message): - r"""The history of variants update. - Attributes: - version_variants (google.cloud.dialogflowcx_v3beta1.types.VersionVariants): - The flow versions as the variants. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Update time of the variants. - """ - - version_variants = proto.Field( - proto.MESSAGE, - number=1, - oneof='variants', - message='VersionVariants', - ) - update_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class ListExperimentsRequest(proto.Message): - r"""The request message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. - - Attributes: - parent (str): - Required. The - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - to list all environments for. Format: - ``projects//locations//agents//environments/``. - page_size (int): - The maximum number of items to return in a - single page. By default 20 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 ListExperimentsResponse(proto.Message): - r"""The response message for - [Experiments.ListExperiments][google.cloud.dialogflow.cx.v3beta1.Experiments.ListExperiments]. - - Attributes: - experiments (Sequence[google.cloud.dialogflowcx_v3beta1.types.Experiment]): - The list of experiments. There will be a maximum number of - items returned based on the page_size field in the request. - The list may in some cases be empty or contain fewer entries - than page_size even if this isn't the last page. - 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 - - experiments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Experiment', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetExperimentRequest(proto.Message): - r"""The request message for - [Experiments.GetExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.GetExperiment]. - - Attributes: - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. - Format: - ``projects//locations//agents//environments//experiments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateExperimentRequest(proto.Message): - r"""The request message for - [Experiments.CreateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.CreateExperiment]. - - Attributes: - parent (str): - Required. The - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent] to create - an - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - for. Format: - ``projects//locations//agents//environments/``. - experiment (google.cloud.dialogflowcx_v3beta1.types.Experiment): - Required. The experiment to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - experiment = proto.Field( - proto.MESSAGE, - number=2, - message='Experiment', - ) - - -class UpdateExperimentRequest(proto.Message): - r"""The request message for - [Experiments.UpdateExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.UpdateExperiment]. - - Attributes: - experiment (google.cloud.dialogflowcx_v3beta1.types.Experiment): - Required. The experiment to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields - get updated. - """ - - experiment = proto.Field( - proto.MESSAGE, - number=1, - message='Experiment', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteExperimentRequest(proto.Message): - r"""The request message for - [Experiments.DeleteExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.DeleteExperiment]. - - Attributes: - name (str): - Required. The name of the - [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] - to delete. Format: - ``projects//locations//agents//environments//experiments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class StartExperimentRequest(proto.Message): - r"""The request message for - [Experiments.StartExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StartExperiment]. - - Attributes: - name (str): - Required. Resource name of the experiment to start. Format: - ``projects//locations//agents//environments//experiments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class StopExperimentRequest(proto.Message): - r"""The request message for - [Experiments.StopExperiment][google.cloud.dialogflow.cx.v3beta1.Experiments.StopExperiment]. - - Attributes: - name (str): - Required. Resource name of the experiment to stop. Format: - ``projects//locations//agents//environments//experiments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/flow.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/flow.py deleted file mode 100644 index 46cd9a9c..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/flow.py +++ /dev/null @@ -1,640 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import validation_message -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'NluSettings', - 'Flow', - 'CreateFlowRequest', - 'DeleteFlowRequest', - 'ListFlowsRequest', - 'ListFlowsResponse', - 'GetFlowRequest', - 'UpdateFlowRequest', - 'TrainFlowRequest', - 'ValidateFlowRequest', - 'GetFlowValidationResultRequest', - 'FlowValidationResult', - 'ImportFlowRequest', - 'ImportFlowResponse', - 'ExportFlowRequest', - 'ExportFlowResponse', - }, -) - - -class NluSettings(proto.Message): - r"""Settings related to NLU. - Attributes: - model_type (google.cloud.dialogflowcx_v3beta1.types.NluSettings.ModelType): - Indicates the type of NLU model. - classification_threshold (float): - 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 no-match event 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. - model_training_mode (google.cloud.dialogflowcx_v3beta1.types.NluSettings.ModelTrainingMode): - Indicates NLU model training mode. - """ - class ModelType(proto.Enum): - r"""NLU model type.""" - MODEL_TYPE_UNSPECIFIED = 0 - MODEL_TYPE_STANDARD = 1 - MODEL_TYPE_ADVANCED = 3 - - class ModelTrainingMode(proto.Enum): - r"""NLU model training mode.""" - MODEL_TRAINING_MODE_UNSPECIFIED = 0 - MODEL_TRAINING_MODE_AUTOMATIC = 1 - MODEL_TRAINING_MODE_MANUAL = 2 - - model_type = proto.Field( - proto.ENUM, - number=1, - enum=ModelType, - ) - classification_threshold = proto.Field( - proto.FLOAT, - number=3, - ) - model_training_mode = proto.Field( - proto.ENUM, - number=4, - enum=ModelTrainingMode, - ) - - -class Flow(proto.Message): - r"""Flows represents the conversation flows when you build your - chatbot agent. - A flow consists of many pages connected by the transition - routes. Conversations always start with the built-in Start Flow - (with an all-0 ID). Transition routes can direct the - conversation session from the current flow (parent flow) to - another flow (sub flow). When the sub flow is finished, - Dialogflow will bring the session back to the parent flow, where - the sub flow is started. - - Usually, when a transition route is followed by a matched - intent, the intent will be "consumed". This means the intent - won't activate more transition routes. However, when the - followed transition route moves the conversation session into a - different flow, the matched intent can be carried over and to be - consumed in the target flow. - - Attributes: - name (str): - The unique identifier of the flow. Format: - ``projects//locations//agents//flows/``. - display_name (str): - Required. The human-readable name of the - flow. - description (str): - The description of the flow. The maximum - length is 500 characters. If exceeded, the - request is rejected. - transition_routes (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRoute]): - A flow's transition routes serve two purposes: - - - They are responsible for matching the user's first - utterances in the flow. - - They are inherited by every page's [transition - routes][Page.transition_routes] and can support use cases - such as the user saying "help" or "can I talk to a - human?", which can be handled in a common way regardless - of the current page. Transition routes defined in the - page have higher priority than those defined in the flow. - - TransitionRoutes are evalauted in the following order: - - - TransitionRoutes with intent specified.. - - TransitionRoutes with only condition specified. - - TransitionRoutes with intent specified are inherited by - pages in the flow. - event_handlers (Sequence[google.cloud.dialogflowcx_v3beta1.types.EventHandler]): - A flow's event handlers serve two purposes: - - - They are responsible for handling events (e.g. no match, - webhook errors) in the flow. - - They are inherited by every page's [event - handlers][Page.event_handlers], which can be used to - handle common events regardless of the current page. - Event handlers defined in the page have higher priority - than those defined in the flow. - - Unlike - [transition_routes][google.cloud.dialogflow.cx.v3beta1.Flow.transition_routes], - these handlers are evaluated on a first-match basis. The - first one that matches the event get executed, with the rest - being ignored. - transition_route_groups (Sequence[str]): - A flow's transition route group serve two purposes: - - - They are responsible for matching the user's first - utterances in the flow. - - They are inherited by every page's [transition route - groups][Page.transition_route_groups]. Transition route - groups defined in the page have higher priority than - those defined in the flow. - - Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. - nlu_settings (google.cloud.dialogflowcx_v3beta1.types.NluSettings): - NLU related settings of the flow. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - transition_routes = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=page.TransitionRoute, - ) - event_handlers = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=page.EventHandler, - ) - transition_route_groups = proto.RepeatedField( - proto.STRING, - number=15, - ) - nlu_settings = proto.Field( - proto.MESSAGE, - number=11, - message='NluSettings', - ) - - -class CreateFlowRequest(proto.Message): - r"""The request message for - [Flows.CreateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.CreateFlow]. - - Attributes: - parent (str): - Required. The agent to create a flow for. Format: - ``projects//locations//agents/``. - flow (google.cloud.dialogflowcx_v3beta1.types.Flow): - Required. The flow to create. - language_code (str): - The language of the following fields in ``flow``: - - - ``Flow.event_handlers.trigger_fulfillment.messages`` - - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Flow.transition_routes.trigger_fulfillment.messages`` - - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - flow = proto.Field( - proto.MESSAGE, - number=2, - message='Flow', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteFlowRequest(proto.Message): - r"""The request message for - [Flows.DeleteFlow][google.cloud.dialogflow.cx.v3beta1.Flows.DeleteFlow]. - - Attributes: - name (str): - Required. The name of the flow to delete. Format: - ``projects//locations//agents//flows/``. - force (bool): - This field has no effect for flows with no incoming - transitions. For flows with incoming transitions: - - - If ``force`` is set to false, an error will be returned - with message indicating the incoming transitions. - - If ``force`` is set to true, Dialogflow will remove the - flow, as well as any transitions to the flow (i.e. - [Target flow][EventHandler.target_flow] in event handlers - or [Target flow][TransitionRoute.target_flow] in - transition routes that point to this flow will be - cleared). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -class ListFlowsRequest(proto.Message): - r"""The request message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. - - Attributes: - parent (str): - Required. The agent containing the flows. Format: - ``projects//locations//agents/``. - 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. - language_code (str): - The language to list flows for. The following fields are - language dependent: - - - ``Flow.event_handlers.trigger_fulfillment.messages`` - - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Flow.transition_routes.trigger_fulfillment.messages`` - - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - - -class ListFlowsResponse(proto.Message): - r"""The response message for - [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. - - Attributes: - flows (Sequence[google.cloud.dialogflowcx_v3beta1.types.Flow]): - The list of flows. 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 - - flows = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Flow', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetFlowRequest(proto.Message): - r"""The response message for - [Flows.GetFlow][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlow]. - - Attributes: - name (str): - Required. The name of the flow to get. Format: - ``projects//locations//agents//flows/``. - language_code (str): - The language to retrieve the flow for. The following fields - are language dependent: - - - ``Flow.event_handlers.trigger_fulfillment.messages`` - - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Flow.transition_routes.trigger_fulfillment.messages`` - - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateFlowRequest(proto.Message): - r"""The request message for - [Flows.UpdateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.UpdateFlow]. - - Attributes: - flow (google.cloud.dialogflowcx_v3beta1.types.Flow): - Required. The flow to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields get updated. If - ``update_mask`` is not specified, an error will be returned. - language_code (str): - The language of the following fields in ``flow``: - - - ``Flow.event_handlers.trigger_fulfillment.messages`` - - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Flow.transition_routes.trigger_fulfillment.messages`` - - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - flow = proto.Field( - proto.MESSAGE, - number=1, - message='Flow', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class TrainFlowRequest(proto.Message): - r"""The request message for - [Flows.TrainFlow][google.cloud.dialogflow.cx.v3beta1.Flows.TrainFlow]. - - Attributes: - name (str): - Required. The flow to train. Format: - ``projects//locations//agents//flows/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class ValidateFlowRequest(proto.Message): - r"""The request message for - [Flows.ValidateFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ValidateFlow]. - - Attributes: - name (str): - Required. The flow to validate. Format: - ``projects//locations//agents//flows/``. - language_code (str): - If not specified, the agent's default - language is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class GetFlowValidationResultRequest(proto.Message): - r"""The request message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. - - Attributes: - name (str): - Required. The flow name. Format: - ``projects//locations//agents//flows//validationResult``. - language_code (str): - If not specified, the agent's default - language is used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class FlowValidationResult(proto.Message): - r"""The response message for - [Flows.GetFlowValidationResult][google.cloud.dialogflow.cx.v3beta1.Flows.GetFlowValidationResult]. - - Attributes: - name (str): - The unique identifier of the flow validation result. Format: - ``projects//locations//agents//flows//validationResult``. - validation_messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ValidationMessage]): - Contains all validation messages. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Last time the flow was validated. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - validation_messages = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=validation_message.ValidationMessage, - ) - update_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class ImportFlowRequest(proto.Message): - r"""The request message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. - - Attributes: - parent (str): - Required. The agent to import the flow into. Format: - ``projects//locations//agents/``. - flow_uri (str): - The `Google Cloud - Storage `__ URI to - import flow from. The format of this URI must be - ``gs:///``. - flow_content (bytes): - Uncompressed raw byte content for flow. - import_option (google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest.ImportOption): - Flow import mode. If not specified, ``KEEP`` is assumed. - """ - class ImportOption(proto.Enum): - r"""Import option.""" - IMPORT_OPTION_UNSPECIFIED = 0 - KEEP = 1 - FALLBACK = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - flow_uri = proto.Field( - proto.STRING, - number=2, - oneof='flow', - ) - flow_content = proto.Field( - proto.BYTES, - number=3, - oneof='flow', - ) - import_option = proto.Field( - proto.ENUM, - number=4, - enum=ImportOption, - ) - - -class ImportFlowResponse(proto.Message): - r"""The response message for - [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. - - Attributes: - flow (str): - The unique identifier of the new flow. Format: - ``projects//locations//agents//flows/``. - """ - - flow = proto.Field( - proto.STRING, - number=1, - ) - - -class ExportFlowRequest(proto.Message): - r"""The request message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. - - Attributes: - name (str): - Required. The name of the flow to export. Format: - ``projects//locations//agents//flows/``. - flow_uri (str): - Optional. The `Google Cloud - Storage `__ URI to - export the flow to. The format of this URI must be - ``gs:///``. If left unspecified, - the serialized flow is returned inline. - include_referenced_flows (bool): - Optional. Whether to export flows referenced - by the specified flow. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - flow_uri = proto.Field( - proto.STRING, - number=2, - ) - include_referenced_flows = proto.Field( - proto.BOOL, - number=4, - ) - - -class ExportFlowResponse(proto.Message): - r"""The response message for - [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. - - Attributes: - flow_uri (str): - The URI to a file containing the exported flow. This field - is populated only if ``flow_uri`` is specified in - [ExportFlowRequest][google.cloud.dialogflow.cx.v3beta1.ExportFlowRequest]. - flow_content (bytes): - Uncompressed raw byte content for flow. - """ - - flow_uri = proto.Field( - proto.STRING, - number=1, - oneof='flow', - ) - flow_content = proto.Field( - proto.BYTES, - number=2, - oneof='flow', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py deleted file mode 100644 index ca030695..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py +++ /dev/null @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import response_message -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'Fulfillment', - }, -) - - -class Fulfillment(proto.Message): - r"""A fulfillment can do one or more of the following actions at the - same time: - - - Generate rich message responses. - - Set parameter values. - - Call the webhook. - - Fulfillments can be called at various stages in the - [Page][google.cloud.dialogflow.cx.v3beta1.Page] or - [Form][google.cloud.dialogflow.cx.v3beta1.Form] lifecycle. For - example, when a - [DetectIntentRequest][google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest] - drives a session to enter a new page, the page's entry fulfillment - can add a static response to the - [QueryResult][google.cloud.dialogflow.cx.v3beta1.QueryResult] in the - returning - [DetectIntentResponse][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse], - call the webhook (for example, to load user data from a database), - or both. - - Attributes: - messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage]): - The list of rich message responses to present - to the user. - webhook (str): - The webhook to call. Format: - ``projects//locations//agents//webhooks/``. - tag (str): - The tag used by the webhook to identify which fulfillment is - being called. This field is required if ``webhook`` is - specified. - set_parameter_actions (Sequence[google.cloud.dialogflowcx_v3beta1.types.Fulfillment.SetParameterAction]): - Set parameter values before executing the - webhook. - conditional_cases (Sequence[google.cloud.dialogflowcx_v3beta1.types.Fulfillment.ConditionalCases]): - Conditional cases for this fulfillment. - """ - - class SetParameterAction(proto.Message): - r"""Setting a parameter value. - Attributes: - parameter (str): - Display name of the parameter. - value (google.protobuf.struct_pb2.Value): - The new value of the parameter. A null value - clears the parameter. - """ - - parameter = proto.Field( - proto.STRING, - number=1, - ) - value = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - class ConditionalCases(proto.Message): - r"""A list of cascading if-else conditions. Cases are mutually - exclusive. The first one with a matching condition is selected, - all the rest ignored. - - Attributes: - cases (Sequence[google.cloud.dialogflowcx_v3beta1.types.Fulfillment.ConditionalCases.Case]): - A list of cascading if-else conditions. - """ - - class Case(proto.Message): - r"""Each case has a Boolean condition. When it is evaluated to be - True, the corresponding messages will be selected and evaluated - recursively. - - Attributes: - condition (str): - The condition to activate and select this case. Empty means - the condition is always true. The condition is evaluated - against [form parameters][Form.parameters] or [session - parameters][SessionInfo.parameters]. - - See the `conditions - reference `__. - case_content (Sequence[google.cloud.dialogflowcx_v3beta1.types.Fulfillment.ConditionalCases.Case.CaseContent]): - A list of case content. - """ - - class CaseContent(proto.Message): - r"""The list of messages or conditional cases to activate for - this case. - - Attributes: - message (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage): - Returned message. - additional_cases (google.cloud.dialogflowcx_v3beta1.types.Fulfillment.ConditionalCases): - Additional cases to be evaluated. - """ - - message = proto.Field( - proto.MESSAGE, - number=1, - oneof='cases_or_message', - message=response_message.ResponseMessage, - ) - additional_cases = proto.Field( - proto.MESSAGE, - number=2, - oneof='cases_or_message', - message='Fulfillment.ConditionalCases', - ) - - condition = proto.Field( - proto.STRING, - number=1, - ) - case_content = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Fulfillment.ConditionalCases.Case.CaseContent', - ) - - cases = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Fulfillment.ConditionalCases.Case', - ) - - messages = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=response_message.ResponseMessage, - ) - webhook = proto.Field( - proto.STRING, - number=2, - ) - tag = proto.Field( - proto.STRING, - number=3, - ) - set_parameter_actions = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=SetParameterAction, - ) - conditional_cases = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=ConditionalCases, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/intent.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/intent.py deleted file mode 100644 index 656933f6..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/intent.py +++ /dev/null @@ -1,474 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cx.v3beta1', - manifest={ - 'IntentView', - 'Intent', - 'ListIntentsRequest', - 'ListIntentsResponse', - 'GetIntentRequest', - 'CreateIntentRequest', - 'UpdateIntentRequest', - 'DeleteIntentRequest', - }, -) - - -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. - """ - INTENT_VIEW_UNSPECIFIED = 0 - INTENT_VIEW_PARTIAL = 1 - INTENT_VIEW_FULL = 2 - - -class Intent(proto.Message): - r"""An intent represents a user's intent to interact with a - conversational agent. - You can provide information for the Dialogflow API to use to - match user input to an intent by adding training phrases (i.e., - examples of user input) to your intent. - - Attributes: - name (str): - The unique identifier of the intent. Required for the - [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.UpdateIntent] - method. - [Intents.CreateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.CreateIntent] - populates the name automatically. Format: - ``projects//locations//agents//intents/``. - display_name (str): - Required. The human-readable name of the - intent, unique within the agent. - training_phrases (Sequence[google.cloud.dialogflowcx_v3beta1.types.Intent.TrainingPhrase]): - The collection of training phrases the agent - is trained on to identify the intent. - parameters (Sequence[google.cloud.dialogflowcx_v3beta1.types.Intent.Parameter]): - The collection of parameters associated with - the intent. - priority (int): - 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): - Indicates whether this is a fallback intent. - Currently only default fallback intent is - allowed in the agent, which is added upon agent - creation. - Adding training phrases to fallback intent is - useful in the case of requests that are - mistakenly matched, since training phrases - assigned to fallback intents act as negative - examples that triggers no-match event. - labels (Sequence[google.cloud.dialogflowcx_v3beta1.types.Intent.LabelsEntry]): - The key/value metadata to label an intent. Labels can - contain lowercase letters, digits and the symbols '-' and - '_'. International characters are allowed, including letters - from unicase alphabets. Keys must start with a letter. Keys - and values can be no longer than 63 characters and no more - than 128 bytes. - - Prefix "sys-" is reserved for Dialogflow defined labels. - Currently allowed Dialogflow defined labels include: - - - sys-head - - sys-contextual The above labels do not require value. - "sys-head" means the intent is a head intent. - "sys-contextual" means the intent is a contextual intent. - description (str): - Human readable description for better - understanding an intent like its scope, content, - result etc. Maximum character limit: 140 - characters. - """ - - class TrainingPhrase(proto.Message): - r"""Represents an example that the agent is trained on to - identify the intent. - - Attributes: - id (str): - Output only. The unique identifier of the - training phrase. - parts (Sequence[google.cloud.dialogflowcx_v3beta1.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.cx.v3beta1.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 ``parameter_id`` field is set. - repeat_count (int): - Indicates how many times this example was - added to the intent. - """ - - class Part(proto.Message): - r"""Represents a part of a training phrase. - Attributes: - text (str): - Required. The text for this part. - parameter_id (str): - The - [parameter][google.cloud.dialogflow.cx.v3beta1.Intent.Parameter] - used to annotate this part of the training phrase. This - field is required for annotated parts of the training - phrase. - """ - - text = proto.Field( - proto.STRING, - number=1, - ) - parameter_id = proto.Field( - proto.STRING, - number=2, - ) - - id = proto.Field( - proto.STRING, - number=1, - ) - parts = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Intent.TrainingPhrase.Part', - ) - repeat_count = proto.Field( - proto.INT32, - number=3, - ) - - class Parameter(proto.Message): - r"""Represents an intent parameter. - Attributes: - id (str): - Required. The unique identifier of the parameter. This field - is used by [training - phrases][google.cloud.dialogflow.cx.v3beta1.Intent.TrainingPhrase] - to annotate their - [parts][google.cloud.dialogflow.cx.v3beta1.Intent.TrainingPhrase.Part]. - entity_type (str): - Required. The entity type of the parameter. Format: - ``projects/-/locations/-/agents/-/entityTypes/`` - for system entity types (for example, - ``projects/-/locations/-/agents/-/entityTypes/sys.date``), - or - ``projects//locations//agents//entityTypes/`` - for developer entity types. - is_list (bool): - Indicates whether the parameter represents a - list of values. - redact (bool): - Indicates whether the parameter content should be redacted - in log. If redaction is enabled, the parameter content will - be replaced by parameter name during logging. Note: the - parameter content is subject to redaction if either - parameter level redaction or [entity type level - redaction][google.cloud.dialogflow.cx.v3beta1.EntityType.redact] - is enabled. - """ - - id = proto.Field( - proto.STRING, - number=1, - ) - entity_type = proto.Field( - proto.STRING, - number=2, - ) - is_list = proto.Field( - proto.BOOL, - number=3, - ) - redact = proto.Field( - proto.BOOL, - number=4, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - training_phrases = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=TrainingPhrase, - ) - parameters = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Parameter, - ) - priority = proto.Field( - proto.INT32, - number=5, - ) - is_fallback = proto.Field( - proto.BOOL, - number=6, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - description = proto.Field( - proto.STRING, - number=8, - ) - - -class ListIntentsRequest(proto.Message): - r"""The request message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.Intents.ListIntents]. - - Attributes: - parent (str): - Required. The agent to list all intents for. Format: - ``projects//locations//agents/``. - language_code (str): - The language to list intents for. The following fields are - language dependent: - - - ``Intent.training_phrases.parts.text`` - - 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. - intent_view (google.cloud.dialogflowcx_v3beta1.types.IntentView): - The resource view to apply to the returned - intent. - 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, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - intent_view = proto.Field( - proto.ENUM, - number=5, - enum='IntentView', - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListIntentsResponse(proto.Message): - r"""The response message for - [Intents.ListIntents][google.cloud.dialogflow.cx.v3beta1.Intents.ListIntents]. - - Attributes: - intents (Sequence[google.cloud.dialogflowcx_v3beta1.types.Intent]): - The list of 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.cx.v3beta1.Intents.GetIntent]. - - Attributes: - name (str): - Required. The name of the intent. Format: - ``projects//locations//agents//intents/``. - language_code (str): - The language to retrieve the intent for. The following - fields are language dependent: - - - ``Intent.training_phrases.parts.text`` - - 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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateIntentRequest(proto.Message): - r"""The request message for - [Intents.CreateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.CreateIntent]. - - Attributes: - parent (str): - Required. The agent to create an intent for. Format: - ``projects//locations//agents/``. - intent (google.cloud.dialogflowcx_v3beta1.types.Intent): - Required. The intent to create. - language_code (str): - The language of the following fields in ``intent``: - - - ``Intent.training_phrases.parts.text`` - - 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, - ) - intent = proto.Field( - proto.MESSAGE, - number=2, - message='Intent', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateIntentRequest(proto.Message): - r"""The request message for - [Intents.UpdateIntent][google.cloud.dialogflow.cx.v3beta1.Intents.UpdateIntent]. - - Attributes: - intent (google.cloud.dialogflowcx_v3beta1.types.Intent): - Required. The intent to update. - language_code (str): - The language of the following fields in ``intent``: - - - ``Intent.training_phrases.parts.text`` - - 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. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The mask to control which fields get updated. - If the mask is not present, all fields will be - updated. - """ - - 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, - ) - - -class DeleteIntentRequest(proto.Message): - r"""The request message for - [Intents.DeleteIntent][google.cloud.dialogflow.cx.v3beta1.Intents.DeleteIntent]. - - Attributes: - name (str): - Required. The name of the intent to delete. Format: - ``projects//locations//agents//intents/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/page.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/page.py deleted file mode 100644 index aff9f8da..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/page.py +++ /dev/null @@ -1,730 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import fulfillment -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'Page', - 'Form', - 'EventHandler', - 'TransitionRoute', - 'ListPagesRequest', - 'ListPagesResponse', - 'GetPageRequest', - 'CreatePageRequest', - 'UpdatePageRequest', - 'DeletePageRequest', - }, -) - - -class Page(proto.Message): - r"""A Dialogflow CX conversation (session) can be described and - visualized as a state machine. The states of a CX session are - represented by pages. - - For each flow, you define many pages, where your combined pages can - handle a complete conversation on the topics the flow is designed - for. At any given moment, exactly one page is the current page, the - current page is considered active, and the flow associated with that - page is considered active. Every flow has a special start page. When - a flow initially becomes active, the start page page becomes the - current page. For each conversational turn, the current page will - either stay the same or transition to another page. - - You configure each page to collect information from the end-user - that is relevant for the conversational state represented by the - page. - - For more information, see the `Page - guide `__. - - Attributes: - name (str): - The unique identifier of the page. Required for the - [Pages.UpdatePage][google.cloud.dialogflow.cx.v3beta1.Pages.UpdatePage] - method. - [Pages.CreatePage][google.cloud.dialogflow.cx.v3beta1.Pages.CreatePage] - populates the name automatically. Format: - ``projects//locations//agents//flows//pages/``. - display_name (str): - Required. The human-readable name of the - page, unique within the agent. - entry_fulfillment (google.cloud.dialogflowcx_v3beta1.types.Fulfillment): - The fulfillment to call when the session is - entering the page. - form (google.cloud.dialogflowcx_v3beta1.types.Form): - The form associated with the page, used for - collecting parameters relevant to the page. - transition_route_groups (Sequence[str]): - Ordered list of - [``TransitionRouteGroups``][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - associated with the page. Transition route groups must be - unique within a page. - - - If multiple transition routes within a page scope refer - to the same intent, then the precedence order is: page's - transition route -> page's transition route group -> - flow's transition routes. - - - If multiple transition route groups within a page contain - the same intent, then the first group in the ordered list - takes precedence. - - Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. - transition_routes (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRoute]): - A list of transitions for the transition rules of this page. - They route the conversation to another page in the same - flow, or another flow. - - When we are in a certain page, the TransitionRoutes are - evalauted in the following order: - - - TransitionRoutes defined in the page with intent - specified. - - TransitionRoutes defined in the [transition route - groups][google.cloud.dialogflow.cx.v3beta1.Page.transition_route_groups] - with intent specified. - - TransitionRoutes defined in flow with intent specified. - - TransitionRoutes defined in the [transition route - groups][google.cloud.dialogflow.cx.v3beta1.Flow.transition_route_groups] - with intent specified. - - TransitionRoutes defined in the page with only condition - specified. - - TransitionRoutes defined in the [transition route - groups][google.cloud.dialogflow.cx.v3beta1.Page.transition_route_groups] - with only condition specified. - event_handlers (Sequence[google.cloud.dialogflowcx_v3beta1.types.EventHandler]): - Handlers associated with the page to handle - events such as webhook errors, no match or no - input. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - entry_fulfillment = proto.Field( - proto.MESSAGE, - number=7, - message=fulfillment.Fulfillment, - ) - form = proto.Field( - proto.MESSAGE, - number=4, - message='Form', - ) - transition_route_groups = proto.RepeatedField( - proto.STRING, - number=11, - ) - transition_routes = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='TransitionRoute', - ) - event_handlers = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='EventHandler', - ) - - -class Form(proto.Message): - r"""A form is a data model that groups related parameters that can be - collected from the user. The process in which the agent prompts the - user and collects parameter values from the user is called form - filling. A form can be added to a - [page][google.cloud.dialogflow.cx.v3beta1.Page]. When form filling - is done, the filled parameters will be written to the - [session][google.cloud.dialogflow.cx.v3beta1.SessionInfo.parameters]. - - Attributes: - parameters (Sequence[google.cloud.dialogflowcx_v3beta1.types.Form.Parameter]): - Parameters to collect from the user. - """ - - class Parameter(proto.Message): - r"""Represents a form parameter. - Attributes: - display_name (str): - Required. The human-readable name of the - parameter, unique within the form. - required (bool): - Indicates whether the parameter is required. - Optional parameters will not trigger prompts; - however, they are filled if the user specifies - them. Required parameters must be filled before - form filling concludes. - entity_type (str): - Required. The entity type of the parameter. Format: - ``projects/-/locations/-/agents/-/entityTypes/`` - for system entity types (for example, - ``projects/-/locations/-/agents/-/entityTypes/sys.date``), - or - ``projects//locations//agents//entityTypes/`` - for developer entity types. - is_list (bool): - Indicates whether the parameter represents a - list of values. - fill_behavior (google.cloud.dialogflowcx_v3beta1.types.Form.Parameter.FillBehavior): - Required. Defines fill behavior for the - parameter. - default_value (google.protobuf.struct_pb2.Value): - The default value of an optional parameter. - If the parameter is required, the default value - will be ignored. - redact (bool): - Indicates whether the parameter content should be redacted - in log. If redaction is enabled, the parameter content will - be replaced by parameter name during logging. Note: the - parameter content is subject to redaction if either - parameter level redaction or [entity type level - redaction][google.cloud.dialogflow.cx.v3beta1.EntityType.redact] - is enabled. - """ - - class FillBehavior(proto.Message): - r"""Configuration for how the filling of a parameter should be - handled. - - Attributes: - initial_prompt_fulfillment (google.cloud.dialogflowcx_v3beta1.types.Fulfillment): - Required. The fulfillment to provide the - initial prompt that the agent can present to the - user in order to fill the parameter. - reprompt_event_handlers (Sequence[google.cloud.dialogflowcx_v3beta1.types.EventHandler]): - The handlers for parameter-level events, used to provide - reprompt for the parameter or transition to a different - page/flow. The supported events are: - - - ``sys.no-match-``, where N can be from 1 to 6 - - ``sys.no-match-default`` - - ``sys.no-input-``, where N can be from 1 to 6 - - ``sys.no-input-default`` - - ``sys.invalid-parameter`` - - ``initial_prompt_fulfillment`` provides the first prompt for - the parameter. - - If the user's response does not fill the parameter, a - no-match/no-input event will be triggered, and the - fulfillment associated with the - ``sys.no-match-1``/``sys.no-input-1`` handler (if defined) - will be called to provide a prompt. The - ``sys.no-match-2``/``sys.no-input-2`` handler (if defined) - will respond to the next no-match/no-input event, and so on. - - A ``sys.no-match-default`` or ``sys.no-input-default`` - handler will be used to handle all following - no-match/no-input events after all numbered - no-match/no-input handlers for the parameter are consumed. - - A ``sys.invalid-parameter`` handler can be defined to handle - the case where the parameter values have been - ``invalidated`` by webhook. For example, if the user's - response fill the parameter, however the parameter was - invalidated by webhook, the fulfillment associated with the - ``sys.invalid-parameter`` handler (if defined) will be - called to provide a prompt. - - If the event handler for the corresponding event can't be - found on the parameter, ``initial_prompt_fulfillment`` will - be re-prompted. - """ - - initial_prompt_fulfillment = proto.Field( - proto.MESSAGE, - number=3, - message=fulfillment.Fulfillment, - ) - reprompt_event_handlers = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='EventHandler', - ) - - display_name = proto.Field( - proto.STRING, - number=1, - ) - required = proto.Field( - proto.BOOL, - number=2, - ) - entity_type = proto.Field( - proto.STRING, - number=3, - ) - is_list = proto.Field( - proto.BOOL, - number=4, - ) - fill_behavior = proto.Field( - proto.MESSAGE, - number=7, - message='Form.Parameter.FillBehavior', - ) - default_value = proto.Field( - proto.MESSAGE, - number=9, - message=struct_pb2.Value, - ) - redact = proto.Field( - proto.BOOL, - number=11, - ) - - parameters = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Parameter, - ) - - -class EventHandler(proto.Message): - r"""An event handler specifies an - [event][google.cloud.dialogflow.cx.v3beta1.EventHandler.event] that - can be handled during a session. When the specified event happens, - the following actions are taken in order: - - - If there is a - [``trigger_fulfillment``][google.cloud.dialogflow.cx.v3beta1.EventHandler.trigger_fulfillment] - associated with the event, it will be called. - - If there is a - [``target_page``][google.cloud.dialogflow.cx.v3beta1.EventHandler.target_page] - associated with the event, the session will transition into the - specified page. - - If there is a - [``target_flow``][google.cloud.dialogflow.cx.v3beta1.EventHandler.target_flow] - associated with the event, the session will transition into the - specified flow. - - Attributes: - name (str): - Output only. The unique identifier of this - event handler. - event (str): - Required. The name of the event to handle. - trigger_fulfillment (google.cloud.dialogflowcx_v3beta1.types.Fulfillment): - The fulfillment to call when the event - occurs. Handling webhook errors with a - fulfillment enabled with webhook could cause - infinite loop. It is invalid to specify such - fulfillment for a handler handling webhooks. - target_page (str): - The target page to transition to. Format: - ``projects//locations//agents//flows//pages/``. - target_flow (str): - The target flow to transition to. Format: - ``projects//locations//agents//flows/``. - """ - - name = proto.Field( - proto.STRING, - number=6, - ) - event = proto.Field( - proto.STRING, - number=4, - ) - trigger_fulfillment = proto.Field( - proto.MESSAGE, - number=5, - message=fulfillment.Fulfillment, - ) - target_page = proto.Field( - proto.STRING, - number=2, - oneof='target', - ) - target_flow = proto.Field( - proto.STRING, - number=3, - oneof='target', - ) - - -class TransitionRoute(proto.Message): - r"""A transition route specifies a - [intent][google.cloud.dialogflow.cx.v3beta1.Intent] that can be - matched and/or a data condition that can be evaluated during a - session. When a specified transition is matched, the following - actions are taken in order: - - - If there is a - [``trigger_fulfillment``][google.cloud.dialogflow.cx.v3beta1.TransitionRoute.trigger_fulfillment] - associated with the transition, it will be called. - - If there is a - [``target_page``][google.cloud.dialogflow.cx.v3beta1.TransitionRoute.target_page] - associated with the transition, the session will transition into - the specified page. - - If there is a - [``target_flow``][google.cloud.dialogflow.cx.v3beta1.TransitionRoute.target_flow] - associated with the transition, the session will transition into - the specified flow. - - Attributes: - name (str): - Output only. The unique identifier of this - transition route. - intent (str): - The unique identifier of an - [Intent][google.cloud.dialogflow.cx.v3beta1.Intent]. Format: - ``projects//locations//agents//intents/``. - Indicates that the transition can only happen when the given - intent is matched. At least one of ``intent`` or - ``condition`` must be specified. When both ``intent`` and - ``condition`` are specified, the transition can only happen - when both are fulfilled. - condition (str): - The condition to evaluate against [form - parameters][google.cloud.dialogflow.cx.v3beta1.Form.parameters] - or [session - parameters][google.cloud.dialogflow.cx.v3beta1.SessionInfo.parameters]. - - See the `conditions - reference `__. - At least one of ``intent`` or ``condition`` must be - specified. When both ``intent`` and ``condition`` are - specified, the transition can only happen when both are - fulfilled. - trigger_fulfillment (google.cloud.dialogflowcx_v3beta1.types.Fulfillment): - The fulfillment to call when the condition is satisfied. At - least one of ``trigger_fulfillment`` and ``target`` must be - specified. When both are defined, ``trigger_fulfillment`` is - executed first. - target_page (str): - The target page to transition to. Format: - ``projects//locations//agents//flows//pages/``. - target_flow (str): - The target flow to transition to. Format: - ``projects//locations//agents//flows/``. - """ - - name = proto.Field( - proto.STRING, - number=6, - ) - intent = proto.Field( - proto.STRING, - number=1, - ) - condition = proto.Field( - proto.STRING, - number=2, - ) - trigger_fulfillment = proto.Field( - proto.MESSAGE, - number=3, - message=fulfillment.Fulfillment, - ) - target_page = proto.Field( - proto.STRING, - number=4, - oneof='target', - ) - target_flow = proto.Field( - proto.STRING, - number=5, - oneof='target', - ) - - -class ListPagesRequest(proto.Message): - r"""The request message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. - - Attributes: - parent (str): - Required. The flow to list all pages for. Format: - ``projects//locations//agents//flows/``. - language_code (str): - The language to list pages for. The following fields are - language dependent: - - - ``Page.entry_fulfillment.messages`` - - ``Page.entry_fulfillment.conditional_cases`` - - ``Page.event_handlers.trigger_fulfillment.messages`` - - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` - - - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` - - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - 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, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class ListPagesResponse(proto.Message): - r"""The response message for - [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. - - Attributes: - pages (Sequence[google.cloud.dialogflowcx_v3beta1.types.Page]): - The list of pages. 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 - - pages = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Page', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetPageRequest(proto.Message): - r"""The request message for - [Pages.GetPage][google.cloud.dialogflow.cx.v3beta1.Pages.GetPage]. - - Attributes: - name (str): - Required. The name of the page. Format: - ``projects//locations//agents//flows//pages/``. - language_code (str): - The language to retrieve the page for. The following fields - are language dependent: - - - ``Page.entry_fulfillment.messages`` - - ``Page.entry_fulfillment.conditional_cases`` - - ``Page.event_handlers.trigger_fulfillment.messages`` - - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` - - - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` - - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class CreatePageRequest(proto.Message): - r"""The request message for - [Pages.CreatePage][google.cloud.dialogflow.cx.v3beta1.Pages.CreatePage]. - - Attributes: - parent (str): - Required. The flow to create a page for. Format: - ``projects//locations//agents//flows/``. - page (google.cloud.dialogflowcx_v3beta1.types.Page): - Required. The page to create. - language_code (str): - The language of the following fields in ``page``: - - - ``Page.entry_fulfillment.messages`` - - ``Page.entry_fulfillment.conditional_cases`` - - ``Page.event_handlers.trigger_fulfillment.messages`` - - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` - - - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` - - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page = proto.Field( - proto.MESSAGE, - number=2, - message='Page', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdatePageRequest(proto.Message): - r"""The request message for - [Pages.UpdatePage][google.cloud.dialogflow.cx.v3beta1.Pages.UpdatePage]. - - Attributes: - page (google.cloud.dialogflowcx_v3beta1.types.Page): - Required. The page to update. - language_code (str): - The language of the following fields in ``page``: - - - ``Page.entry_fulfillment.messages`` - - ``Page.entry_fulfillment.conditional_cases`` - - ``Page.event_handlers.trigger_fulfillment.messages`` - - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` - - - - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - - - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` - - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The mask to control which fields get updated. - If the mask is not present, all fields will be - updated. - """ - - page = proto.Field( - proto.MESSAGE, - number=1, - message='Page', - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class DeletePageRequest(proto.Message): - r"""The request message for - [Pages.DeletePage][google.cloud.dialogflow.cx.v3beta1.Pages.DeletePage]. - - Attributes: - name (str): - Required. The name of the page to delete. Format: - ``projects//locations//agents//Flows//pages/``. - force (bool): - This field has no effect for pages with no incoming - transitions. For pages with incoming transitions: - - - If ``force`` is set to false, an error will be returned - with message indicating the incoming transitions. - - If ``force`` is set to true, Dialogflow will remove the - page, as well as any transitions to the page (i.e. - [Target page][EventHandler.target_page] in event handlers - or [Target page][TransitionRoute.target_page] in - transition routes that point to this page will be - cleared). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/response_message.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/response_message.py deleted file mode 100644 index 981918e8..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/response_message.py +++ /dev/null @@ -1,340 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'ResponseMessage', - }, -) - - -class ResponseMessage(proto.Message): - r"""Represents a response message that can be returned by a - conversational agent. - - Response messages are also used for output audio synthesis. The - approach is as follows: - - - If at least one OutputAudioText response is present, then all - OutputAudioText responses are linearly concatenated, and the - result is used for output audio synthesis. - - If the OutputAudioText responses are a mixture of text and SSML, - then the concatenated result is treated as SSML; otherwise, the - result is treated as either text or SSML as appropriate. The - agent designer should ideally use either text or SSML - consistently throughout the bot design. - - Otherwise, all Text responses are linearly concatenated, and the - result is used for output audio synthesis. - - This approach allows for more sophisticated user experience - scenarios, where the text displayed to the user may differ from what - is heard. - - Attributes: - text (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.Text): - Returns a text response. - payload (google.protobuf.struct_pb2.Struct): - Returns a response containing a custom, - platform-specific payload. - conversation_success (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.ConversationSuccess): - Indicates that the conversation succeeded. - output_audio_text (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.OutputAudioText): - A text or ssml response that is - preferentially used for TTS output audio - synthesis, as described in the comment on the - ResponseMessage message. - live_agent_handoff (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.LiveAgentHandoff): - Hands off conversation to a human agent. - end_interaction (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.EndInteraction): - Output only. A signal that indicates the interaction with - the Dialogflow agent has ended. This message is generated by - Dialogflow only when the conversation reaches - ``END_SESSION`` page. It is not supposed to be defined by - the user. - - It's guaranteed that there is at most one such message in - each response. - play_audio (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.PlayAudio): - Signal that the client should play an audio clip hosted at a - client-specific URI. Dialogflow uses this to construct - [mixed_audio][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.mixed_audio]. - However, Dialogflow itself does not try to read or process - the URI in any way. - mixed_audio (google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.MixedAudio): - Output only. An audio response message composed of both the - synthesized Dialogflow agent responses and responses defined - via - [play_audio][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.play_audio]. - This message is generated by Dialogflow only and not - supposed to be defined by the user. - """ - - class Text(proto.Message): - r"""The text response message. - Attributes: - text (Sequence[str]): - Required. A collection of text responses. - allow_playback_interruption (bool): - Output only. Whether the playback of this - message can be interrupted by the end user's - speech and the client can then starts the next - Dialogflow request. - """ - - text = proto.RepeatedField( - proto.STRING, - number=1, - ) - allow_playback_interruption = proto.Field( - proto.BOOL, - number=2, - ) - - class LiveAgentHandoff(proto.Message): - r"""Indicates that the conversation should be handed off to a live - 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][google.cloud.dialogflow.cx.v3beta1.Page.entry_fulfillment] - of a [Page][google.cloud.dialogflow.cx.v3beta1.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 ConversationSuccess(proto.Message): - r"""Indicates that the conversation succeeded, i.e., the bot handled the - issue that the customer talked to it about. - - Dialogflow only uses this to determine which conversations should be - counted as successful and doesn't process the metadata in this - message in any way. Note that Dialogflow also considers - conversations that get to the conversation end page as successful - even if they don't return - [ConversationSuccess][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.ConversationSuccess]. - - You may set this, for example: - - - In the - [entry_fulfillment][google.cloud.dialogflow.cx.v3beta1.Page.entry_fulfillment] - of a [Page][google.cloud.dialogflow.cx.v3beta1.Page] if entering - the page indicates that the conversation succeeded. - - In a webhook response when you determine that you handled the - customer issue. - - Attributes: - metadata (google.protobuf.struct_pb2.Struct): - Custom metadata. Dialogflow doesn't impose - any structure on this. - """ - - metadata = proto.Field( - proto.MESSAGE, - number=1, - message=struct_pb2.Struct, - ) - - class OutputAudioText(proto.Message): - r"""A text or ssml response that is preferentially used for TTS - output audio synthesis, as described in the comment on the - ResponseMessage message. - - Attributes: - text (str): - The raw text to be synthesized. - ssml (str): - The SSML text to be synthesized. For more information, see - `SSML `__. - allow_playback_interruption (bool): - Output only. Whether the playback of this - message can be interrupted by the end user's - speech and the client can then starts the next - Dialogflow request. - """ - - text = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - ssml = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - allow_playback_interruption = proto.Field( - proto.BOOL, - number=3, - ) - - class EndInteraction(proto.Message): - r"""Indicates that interaction with the Dialogflow agent has - ended. This message is generated by Dialogflow only and not - supposed to be defined by the user. - """ - - class PlayAudio(proto.Message): - r"""Specifies an audio clip to be played by the client as part of - the response. - - Attributes: - audio_uri (str): - Required. URI of the audio clip. Dialogflow - does not impose any validation on this value. It - is specific to the client that reads it. - allow_playback_interruption (bool): - Output only. Whether the playback of this - message can be interrupted by the end user's - speech and the client can then starts the next - Dialogflow request. - """ - - audio_uri = proto.Field( - proto.STRING, - number=1, - ) - allow_playback_interruption = proto.Field( - proto.BOOL, - number=2, - ) - - class MixedAudio(proto.Message): - r"""Represents an audio message that is composed of both segments - synthesized from the Dialogflow agent prompts and ones hosted - externally at the specified URIs. The external URIs are specified - via - [play_audio][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.play_audio]. - This message is generated by Dialogflow only and not supposed to be - defined by the user. - - Attributes: - segments (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.MixedAudio.Segment]): - Segments this audio response is composed of. - """ - - class Segment(proto.Message): - r"""Represents one segment of audio. - Attributes: - audio (bytes): - Raw audio synthesized from the Dialogflow - agent's response using the output config - specified in the request. - uri (str): - Client-specific URI that points to an audio - clip accessible to the client. Dialogflow does - not impose any validation on it. - allow_playback_interruption (bool): - Output only. Whether the playback of this - segment can be interrupted by the end user's - speech and the client should then start the next - Dialogflow request. - """ - - audio = proto.Field( - proto.BYTES, - number=1, - oneof='content', - ) - uri = proto.Field( - proto.STRING, - number=2, - oneof='content', - ) - allow_playback_interruption = proto.Field( - proto.BOOL, - number=3, - ) - - segments = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ResponseMessage.MixedAudio.Segment', - ) - - text = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message=Text, - ) - payload = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message=struct_pb2.Struct, - ) - conversation_success = proto.Field( - proto.MESSAGE, - number=9, - oneof='message', - message=ConversationSuccess, - ) - output_audio_text = proto.Field( - proto.MESSAGE, - number=8, - oneof='message', - message=OutputAudioText, - ) - live_agent_handoff = proto.Field( - proto.MESSAGE, - number=10, - oneof='message', - message=LiveAgentHandoff, - ) - end_interaction = proto.Field( - proto.MESSAGE, - number=11, - oneof='message', - message=EndInteraction, - ) - play_audio = proto.Field( - proto.MESSAGE, - number=12, - oneof='message', - message=PlayAudio, - ) - mixed_audio = proto.Field( - proto.MESSAGE, - number=13, - oneof='message', - message=MixedAudio, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/security_settings.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/security_settings.py deleted file mode 100644 index 20604349..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/security_settings.py +++ /dev/null @@ -1,267 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cx.v3beta1', - manifest={ - 'GetSecuritySettingsRequest', - 'UpdateSecuritySettingsRequest', - 'ListSecuritySettingsRequest', - 'ListSecuritySettingsResponse', - 'CreateSecuritySettingsRequest', - 'DeleteSecuritySettingsRequest', - 'SecuritySettings', - }, -) - - -class GetSecuritySettingsRequest(proto.Message): - r"""The request message for - [SecuritySettingsService.GetSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.GetSecuritySettings]. - - Attributes: - name (str): - Required. Resource name of the settings. Format: - ``projects//locations//securitySettings/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateSecuritySettingsRequest(proto.Message): - r"""The request message for - [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService.UpdateSecuritySettings]. - - Attributes: - security_settings (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings): - Required. [SecuritySettings] object that contains values for - each of the fields 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. - """ - - security_settings = proto.Field( - proto.MESSAGE, - number=1, - message='SecuritySettings', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListSecuritySettingsRequest(proto.Message): - r"""The request message for [SecuritySettings.ListSecuritySettings][]. - Attributes: - parent (str): - Required. The location to list all security settings for. - Format: ``projects//locations/``. - page_size (int): - The maximum number of items to return in a - single page. By default 20 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 ListSecuritySettingsResponse(proto.Message): - r"""The response message for [SecuritySettings.ListSecuritySettings][]. - Attributes: - security_settings (Sequence[google.cloud.dialogflowcx_v3beta1.types.SecuritySettings]): - The list of security settings. - 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 - - security_settings = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SecuritySettings', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateSecuritySettingsRequest(proto.Message): - r"""The request message for [SecuritySettings.CreateSecuritySettings][]. - Attributes: - parent (str): - Required. The location to create an - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] - for. Format: - ``projects//locations/``. - security_settings (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings): - Required. The security settings to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - security_settings = proto.Field( - proto.MESSAGE, - number=2, - message='SecuritySettings', - ) - - -class DeleteSecuritySettingsRequest(proto.Message): - r"""The request message for [SecuritySettings.DeleteSecuritySettings][]. - Attributes: - name (str): - Required. The name of the - [SecuritySettings][google.cloud.dialogflow.cx.v3beta1.SecuritySettings] - to delete. Format: - ``projects//locations//securitySettings/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class SecuritySettings(proto.Message): - r"""Represents the settings related to security issues, such as - data redaction and data retention. It may take hours for updates - on the settings to propagate to all the related components and - take effect. - - Attributes: - name (str): - Required. Resource name of the settings. Format: - ``projects//locations//securitySettings/``. - display_name (str): - Required. The human-readable name of the - security settings, unique within the location. - redaction_strategy (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings.RedactionStrategy): - Strategy that defines how we do redaction. - redaction_scope (google.cloud.dialogflowcx_v3beta1.types.SecuritySettings.RedactionScope): - Defines the data for which Dialogflow applies - redaction. Dialogflow does not redact data that - it does not have access to – for example, Cloud - logging. - inspect_template (str): - DLP inspect template name. Use this template to define - inspect base settings. - - If empty, we use the default DLP inspect config. - - The template name will have one of the following formats: - ``projects/PROJECT_ID/inspectTemplates/TEMPLATE_ID`` OR - ``organizations/ORGANIZATION_ID/inspectTemplates/TEMPLATE_ID`` - retention_window_days (int): - Retains data in interaction logging for the - specified number of days. This does not apply to - Cloud logging, which is owned by the user - not - Dialogflow. - User must Set a value lower than Dialogflow's - default 30d TTL. Setting a value higher than - that has no effect. - A missing value or setting to 0 also means we - use Dialogflow's default TTL. - Note: Interaction logging is a limited access - feature. Talk to your Google representative to - check availability for you. - purge_data_types (Sequence[google.cloud.dialogflowcx_v3beta1.types.SecuritySettings.PurgeDataType]): - List of types of data to remove when - retention settings triggers purge. - """ - class RedactionStrategy(proto.Enum): - r"""Defines how we redact data.""" - REDACTION_STRATEGY_UNSPECIFIED = 0 - REDACT_WITH_SERVICE = 1 - - class RedactionScope(proto.Enum): - r"""Defines what types of data to redact.""" - REDACTION_SCOPE_UNSPECIFIED = 0 - REDACT_DISK_STORAGE = 2 - - class PurgeDataType(proto.Enum): - r"""Type of data we purge after retention settings triggers - purge. - """ - PURGE_DATA_TYPE_UNSPECIFIED = 0 - DIALOGFLOW_HISTORY = 1 - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - redaction_strategy = proto.Field( - proto.ENUM, - number=3, - enum=RedactionStrategy, - ) - redaction_scope = proto.Field( - proto.ENUM, - number=4, - enum=RedactionScope, - ) - inspect_template = proto.Field( - proto.STRING, - number=9, - ) - retention_window_days = proto.Field( - proto.INT32, - number=6, - oneof='data_retention', - ) - purge_data_types = proto.RepeatedField( - proto.ENUM, - number=8, - enum=PurgeDataType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session.py deleted file mode 100644 index beba7b99..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session.py +++ /dev/null @@ -1,1172 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import audio_config -from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import response_message -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type -from google.protobuf import duration_pb2 # 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.cx.v3beta1', - manifest={ - 'DetectIntentRequest', - 'DetectIntentResponse', - 'StreamingDetectIntentRequest', - 'StreamingDetectIntentResponse', - 'StreamingRecognitionResult', - 'QueryParameters', - 'QueryInput', - 'QueryResult', - 'TextInput', - 'IntentInput', - 'AudioInput', - 'EventInput', - 'DtmfInput', - 'Match', - 'MatchIntentRequest', - 'MatchIntentResponse', - 'FulfillIntentRequest', - 'FulfillIntentResponse', - 'SentimentAnalysisResult', - }, -) - - -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//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. It's up to the API caller to choose an - appropriate ``Session ID``. It can be a random number or - some type of session identifiers (preferably hashed). The - length of the ``Session ID`` must not exceed 36 characters. - - For more information, see the `sessions - guide `__. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - query_params (google.cloud.dialogflowcx_v3beta1.types.QueryParameters): - The parameters of this query. - query_input (google.cloud.dialogflowcx_v3beta1.types.QueryInput): - Required. The input specification. - output_audio_config (google.cloud.dialogflowcx_v3beta1.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate the output audio. - """ - - session = proto.Field( - proto.STRING, - number=1, - ) - query_params = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=4, - message=audio_config.OutputAudioConfig, - ) - - -class DetectIntentResponse(proto.Message): - r"""The message returned from the DetectIntent method. - Attributes: - response_id (str): - Output only. 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.dialogflowcx_v3beta1.types.QueryResult): - The result of the conversational query. - 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.response_messages``][google.cloud.dialogflow.cx.v3beta1.QueryResult.response_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.dialogflowcx_v3beta1.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', - ) - output_audio = proto.Field( - proto.BYTES, - number=4, - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=5, - message=audio_config.OutputAudioConfig, - ) - - -class StreamingDetectIntentRequest(proto.Message): - r"""The top-level message sent by the client to the - [Sessions.StreamingDetectIntent][google.cloud.dialogflow.cx.v3beta1.Sessions.StreamingDetectIntent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [session][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.session], - [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] - plus optionally - [query_params][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_params]. - If the client wants to receive an audio response, it should also - contain - [output_audio_config][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.output_audio_config]. - - 2. If - [query_input][google.cloud.dialogflow.cx.v3beta1.StreamingDetectIntentRequest.query_input] - was set to - [query_input.audio.config][google.cloud.dialogflow.cx.v3beta1.AudioInput.config], - all subsequent messages must contain - [query_input.audio.audio][google.cloud.dialogflow.cx.v3beta1.AudioInput.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.cx.v3beta1.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): - The name of the session this query is sent to. Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. It's up to the API caller to choose an - appropriate ``Session ID``. It can be a random number or - some type of session identifiers (preferably hashed). The - length of the ``Session ID`` must not exceed 36 characters. - Note: session must be set in the first request. - - For more information, see the `sessions - guide `__. - - Note: Always use agent versions for production traffic. See - `Versions and - environments `__. - query_params (google.cloud.dialogflowcx_v3beta1.types.QueryParameters): - The parameters of this query. - query_input (google.cloud.dialogflowcx_v3beta1.types.QueryInput): - Required. The input specification. - output_audio_config (google.cloud.dialogflowcx_v3beta1.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate the output audio. - """ - - session = proto.Field( - proto.STRING, - number=1, - ) - query_params = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=4, - message=audio_config.OutputAudioConfig, - ) - - -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. If ``enable_partial_response`` is true, the following N messages - (currently 1 <= N <= 4) contain ``detect_intent_response``. The - first (N-1) ``detect_intent_response``\ s will have - ``response_type`` set to ``PARTIAL``. The last - ``detect_intent_response`` has ``response_type`` set to - ``FINAL``. If ``response_type`` is false, response stream only - contains the final ``detect_intent_response``. - - Attributes: - recognition_result (google.cloud.dialogflowcx_v3beta1.types.StreamingRecognitionResult): - The result of speech recognition. - detect_intent_response (google.cloud.dialogflowcx_v3beta1.types.DetectIntentResponse): - The response from detect intent. - """ - - recognition_result = proto.Field( - proto.MESSAGE, - number=1, - oneof='response', - message='StreamingRecognitionResult', - ) - detect_intent_response = proto.Field( - proto.MESSAGE, - number=2, - oneof='response', - message='DetectIntentResponse', - ) - - -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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.types.SpeechWordInfo]): - Word-specific information for the words recognized by Speech - in - [transcript][google.cloud.dialogflow.cx.v3beta1.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, - ) - stability = proto.Field( - proto.FLOAT, - number=6, - ) - speech_word_info = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=audio_config.SpeechWordInfo, - ) - speech_end_offset = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - - -class QueryParameters(proto.Message): - r"""Represents the parameters of a conversational query. - Attributes: - time_zone (str): - The time zone of this conversational query from the `time - zone database `__, e.g., - America/New_York, Europe/Paris. If not provided, the time - zone specified in the agent is used. - geo_location (google.type.latlng_pb2.LatLng): - The geo location of this conversational - query. - session_entity_types (Sequence[google.cloud.dialogflowcx_v3beta1.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 into the webhook - associated with the agent. Arbitrary JSON objects are - supported. Some integrations that query a Dialogflow agent - may provide additional information in the payload. In - particular, for the Dialogflow Phone Gateway integration, - this field has the form: - - :: - - { - "telephony": { - "caller_id": "+18558363987" - } - } - parameters (google.protobuf.struct_pb2.Struct): - Additional parameters to be put into [session - parameters][SessionInfo.parameters]. To remove a parameter - from the session, clients should explicitly set the - parameter value to null. - - You can reference the session parameters in the agent with - the following format: $session.params.parameter-id. - - 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 - current_page (str): - The unique identifier of the - [page][google.cloud.dialogflow.cx.v3beta1.Page] to override - the [current page][QueryResult.current_page] in the session. - Format: - ``projects//locations//agents//pages/``. - - If ``current_page`` is specified, the previous state of the - session will be ignored by Dialogflow, including the - [previous page][QueryResult.current_page] and the [previous - session parameters][QueryResult.parameters]. In most cases, - [current_page][google.cloud.dialogflow.cx.v3beta1.QueryParameters.current_page] - and - [parameters][google.cloud.dialogflow.cx.v3beta1.QueryParameters.parameters] - should be configured together to direct a session to a - specific state. - disable_webhook (bool): - Whether to disable webhook calls for this - request. - analyze_query_text_sentiment (bool): - Configures whether sentiment analysis should - be performed. If not provided, sentiment - analysis is not performed. - webhook_headers (Sequence[google.cloud.dialogflowcx_v3beta1.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, - ) - session_entity_types = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=session_entity_type.SessionEntityType, - ) - payload = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - parameters = proto.Field( - proto.MESSAGE, - number=5, - message=struct_pb2.Struct, - ) - current_page = proto.Field( - proto.STRING, - number=6, - ) - disable_webhook = proto.Field( - proto.BOOL, - number=7, - ) - analyze_query_text_sentiment = proto.Field( - proto.BOOL, - number=8, - ) - webhook_headers = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - - -class QueryInput(proto.Message): - r"""Represents the query input. It can contain one of: - 1. A conversational query in the form of text. - - 2. An intent query that specifies which intent to trigger. - 3. Natural language speech audio to be processed. - - 4. An event to be triggered. - - Attributes: - text (google.cloud.dialogflowcx_v3beta1.types.TextInput): - The natural language text to be processed. - intent (google.cloud.dialogflowcx_v3beta1.types.IntentInput): - The intent to be triggered. - audio (google.cloud.dialogflowcx_v3beta1.types.AudioInput): - The natural language speech audio to be - processed. - event (google.cloud.dialogflowcx_v3beta1.types.EventInput): - The event to be triggered. - dtmf (google.cloud.dialogflowcx_v3beta1.types.DtmfInput): - The DTMF event to be handled. - language_code (str): - Required. The language of the input. 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.MESSAGE, - number=2, - oneof='input', - message='TextInput', - ) - intent = proto.Field( - proto.MESSAGE, - number=3, - oneof='input', - message='IntentInput', - ) - audio = proto.Field( - proto.MESSAGE, - number=5, - oneof='input', - message='AudioInput', - ) - event = proto.Field( - proto.MESSAGE, - number=6, - oneof='input', - message='EventInput', - ) - dtmf = proto.Field( - proto.MESSAGE, - number=7, - oneof='input', - message='DtmfInput', - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - - -class QueryResult(proto.Message): - r"""Represents the result of a conversational query. - Attributes: - text (str): - If [natural language - text][google.cloud.dialogflow.cx.v3beta1.TextInput] was - provided as input, this field will contain a copy of the - text. - trigger_intent (str): - If an - [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was - provided as input, this field will contain a copy of the - intent identifier. Format: - ``projects//locations//agents//intents/``. - transcript (str): - If [natural language speech - audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was - provided as input, this field will contain the transcript - for the audio. - trigger_event (str): - If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] - was provided as input, this field will contain the name of - the event. - language_code (str): - The language that was triggered during intent detection. See - `Language - Support `__ - for a list of the currently supported language codes. - parameters (google.protobuf.struct_pb2.Struct): - The collected [session - parameters][google.cloud.dialogflow.cx.v3beta1.SessionInfo.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 - response_messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage]): - The list of rich messages returned to the - client. Responses vary from simple text messages - to more sophisticated, structured payloads used - to drive complex logic. - webhook_statuses (Sequence[google.rpc.status_pb2.Status]): - The list of webhook call status in the order - of call sequence. - webhook_payloads (Sequence[google.protobuf.struct_pb2.Struct]): - The list of webhook payload in - [WebhookResponse.payload][google.cloud.dialogflow.cx.v3beta1.WebhookResponse.payload], - in the order of call sequence. If some webhook call fails or - doesn't return any payload, an empty ``Struct`` would be - used instead. - current_page (google.cloud.dialogflowcx_v3beta1.types.Page): - The current [Page][google.cloud.dialogflow.cx.v3beta1.Page]. - Some, not all fields are filled in this message, including - but not limited to ``name`` and ``display_name``. - intent (google.cloud.dialogflowcx_v3beta1.types.Intent): - The [Intent][google.cloud.dialogflow.cx.v3beta1.Intent] that - matched the conversational query. Some, not all fields are - filled in this message, including but not limited to: - ``name`` and ``display_name``. This field is deprecated, - please use - [QueryResult.match][google.cloud.dialogflow.cx.v3beta1.QueryResult.match] - instead. - 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. This field is deprecated, please use - [QueryResult.match][google.cloud.dialogflow.cx.v3beta1.QueryResult.match] - instead. - match (google.cloud.dialogflowcx_v3beta1.types.Match): - Intent match result, could be an intent or an - event. - diagnostic_info (google.protobuf.struct_pb2.Struct): - The free-form diagnostic info. For example, - this field could contain webhook call latency. - The string keys of the Struct's fields map can - change without notice. - sentiment_analysis_result (google.cloud.dialogflowcx_v3beta1.types.SentimentAnalysisResult): - The sentiment analyss result, which depends on - [``analyze_query_text_sentiment``] - [google.cloud.dialogflow.cx.v3beta1.QueryParameters.analyze_query_text_sentiment], - specified in the request. - """ - - text = proto.Field( - proto.STRING, - number=1, - oneof='query', - ) - trigger_intent = proto.Field( - proto.STRING, - number=11, - oneof='query', - ) - transcript = proto.Field( - proto.STRING, - number=12, - oneof='query', - ) - trigger_event = proto.Field( - proto.STRING, - number=14, - oneof='query', - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - parameters = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - response_messages = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=response_message.ResponseMessage, - ) - webhook_statuses = proto.RepeatedField( - proto.MESSAGE, - number=13, - message=status_pb2.Status, - ) - webhook_payloads = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - current_page = proto.Field( - proto.MESSAGE, - number=7, - message=page.Page, - ) - intent = proto.Field( - proto.MESSAGE, - number=8, - message=gcdc_intent.Intent, - ) - intent_detection_confidence = proto.Field( - proto.FLOAT, - number=9, - ) - match = proto.Field( - proto.MESSAGE, - number=15, - message='Match', - ) - diagnostic_info = proto.Field( - proto.MESSAGE, - number=10, - message=struct_pb2.Struct, - ) - sentiment_analysis_result = proto.Field( - proto.MESSAGE, - number=17, - message='SentimentAnalysisResult', - ) - - -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. - """ - - text = proto.Field( - proto.STRING, - number=1, - ) - - -class IntentInput(proto.Message): - r"""Represents the intent to trigger programmatically rather than - as a result of natural language processing. - - Attributes: - intent (str): - Required. The unique identifier of the intent. Format: - ``projects//locations//agents//intents/``. - """ - - intent = proto.Field( - proto.STRING, - number=1, - ) - - -class AudioInput(proto.Message): - r"""Represents the natural speech audio to be processed. - Attributes: - config (google.cloud.dialogflowcx_v3beta1.types.InputAudioConfig): - Required. Instructs the speech recognizer how - to process the speech audio. - audio (bytes): - The natural language speech audio to be processed. A single - request can contain up to 1 minute of speech audio data. The - [transcribed - text][google.cloud.dialogflow.cx.v3beta1.QueryResult.transcript] - cannot contain more than 256 bytes. - - For non-streaming audio detect intent, both ``config`` and - ``audio`` must be provided. For streaming audio detect - intent, ``config`` must be provided in the first request and - ``audio`` must be provided in all following requests. - """ - - config = proto.Field( - proto.MESSAGE, - number=1, - message=audio_config.InputAudioConfig, - ) - audio = proto.Field( - proto.BYTES, - number=2, - ) - - -class EventInput(proto.Message): - r"""Represents the event to trigger. - Attributes: - event (str): - Name of the event. - """ - - event = proto.Field( - proto.STRING, - number=1, - ) - - -class DtmfInput(proto.Message): - r"""Represents the input for dtmf event. - Attributes: - digits (str): - The dtmf digits. - finish_digit (str): - The finish digit (if any). - """ - - digits = proto.Field( - proto.STRING, - number=1, - ) - finish_digit = proto.Field( - proto.STRING, - number=2, - ) - - -class Match(proto.Message): - r"""Represents one match result of [MatchIntent][]. - Attributes: - intent (google.cloud.dialogflowcx_v3beta1.types.Intent): - The [Intent][google.cloud.dialogflow.cx.v3beta1.Intent] that - matched the query. Some, not all fields are filled in this - message, including but not limited to: ``name`` and - ``display_name``. Only filled for - [``INTENT``][google.cloud.dialogflow.cx.v3beta1.Match.MatchType] - match type. - event (str): - The event that matched the query. Only filled for - [``EVENT``][google.cloud.dialogflow.cx.v3beta1.Match.MatchType] - match type. - parameters (google.protobuf.struct_pb2.Struct): - The collection of parameters extracted from - the query. - 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 - resolved_input (str): - Final text input which was matched during - MatchIntent. This value can be different from - original input sent in request because of - spelling correction or other processing. - match_type (google.cloud.dialogflowcx_v3beta1.types.Match.MatchType): - Type of this - [Match][google.cloud.dialogflow.cx.v3beta1.Match]. - confidence (float): - The confidence of this match. Values range - from 0.0 (completely uncertain) to 1.0 - (completely certain). This value is for - informational purpose only and is only used to - help match the best intent within the - classification threshold. This value may change - for the same end-user expression at any time due - to a model retraining or change in - implementation. - """ - class MatchType(proto.Enum): - r"""Type of a Match.""" - MATCH_TYPE_UNSPECIFIED = 0 - INTENT = 1 - DIRECT_INTENT = 2 - PARAMETER_FILLING = 3 - NO_MATCH = 4 - NO_INPUT = 5 - EVENT = 6 - - intent = proto.Field( - proto.MESSAGE, - number=1, - message=gcdc_intent.Intent, - ) - event = proto.Field( - proto.STRING, - number=6, - ) - parameters = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - resolved_input = proto.Field( - proto.STRING, - number=3, - ) - match_type = proto.Field( - proto.ENUM, - number=4, - enum=MatchType, - ) - confidence = proto.Field( - proto.FLOAT, - number=5, - ) - - -class MatchIntentRequest(proto.Message): - r"""Request of [MatchIntent][]. - Attributes: - session (str): - Required. The name of the session this query is sent to. - Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. It's up to the API caller to choose an - appropriate ``Session ID``. It can be a random number or - some type of session identifiers (preferably hashed). The - length of the ``Session ID`` must not exceed 36 characters. - - For more information, see the `sessions - guide `__. - query_params (google.cloud.dialogflowcx_v3beta1.types.QueryParameters): - The parameters of this query. - query_input (google.cloud.dialogflowcx_v3beta1.types.QueryInput): - Required. The input specification. - """ - - session = proto.Field( - proto.STRING, - number=1, - ) - query_params = proto.Field( - proto.MESSAGE, - number=2, - message='QueryParameters', - ) - query_input = proto.Field( - proto.MESSAGE, - number=3, - message='QueryInput', - ) - - -class MatchIntentResponse(proto.Message): - r"""Response of [MatchIntent][]. - Attributes: - text (str): - If [natural language - text][google.cloud.dialogflow.cx.v3beta1.TextInput] was - provided as input, this field will contain a copy of the - text. - trigger_intent (str): - If an - [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was - provided as input, this field will contain a copy of the - intent identifier. Format: - ``projects//locations//agents//intents/``. - transcript (str): - If [natural language speech - audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was - provided as input, this field will contain the transcript - for the audio. - trigger_event (str): - If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] - was provided as input, this field will contain a copy of the - event name. - matches (Sequence[google.cloud.dialogflowcx_v3beta1.types.Match]): - Match results, if more than one, ordered - descendingly by the confidence we have that the - particular intent matches the query. - current_page (google.cloud.dialogflowcx_v3beta1.types.Page): - The current [Page][google.cloud.dialogflow.cx.v3beta1.Page]. - Some, not all fields are filled in this message, including - but not limited to ``name`` and ``display_name``. - """ - - text = proto.Field( - proto.STRING, - number=1, - oneof='query', - ) - trigger_intent = proto.Field( - proto.STRING, - number=2, - oneof='query', - ) - transcript = proto.Field( - proto.STRING, - number=3, - oneof='query', - ) - trigger_event = proto.Field( - proto.STRING, - number=6, - oneof='query', - ) - matches = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Match', - ) - current_page = proto.Field( - proto.MESSAGE, - number=5, - message=page.Page, - ) - - -class FulfillIntentRequest(proto.Message): - r"""Request of [FulfillIntent][] - Attributes: - match_intent_request (google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest): - Must be same as the corresponding MatchIntent - request, otherwise the behavior is undefined. - match (google.cloud.dialogflowcx_v3beta1.types.Match): - The matched intent/event to fulfill. - output_audio_config (google.cloud.dialogflowcx_v3beta1.types.OutputAudioConfig): - Instructs the speech synthesizer how to - generate output audio. - """ - - match_intent_request = proto.Field( - proto.MESSAGE, - number=1, - message='MatchIntentRequest', - ) - match = proto.Field( - proto.MESSAGE, - number=2, - message='Match', - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=3, - message=audio_config.OutputAudioConfig, - ) - - -class FulfillIntentResponse(proto.Message): - r"""Response of [FulfillIntent][] - Attributes: - response_id (str): - Output only. 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.dialogflowcx_v3beta1.types.QueryResult): - The result of the conversational query. - 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.response_messages``][google.cloud.dialogflow.cx.v3beta1.QueryResult.response_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.dialogflowcx_v3beta1.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', - ) - output_audio = proto.Field( - proto.BYTES, - number=3, - ) - output_audio_config = proto.Field( - proto.MESSAGE, - number=4, - message=audio_config.OutputAudioConfig, - ) - - -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. - - 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/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py deleted file mode 100644 index df46a297..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.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 proto # type: ignore - -from google.cloud.dialogflowcx_v3beta1.types import entity_type -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'SessionEntityType', - 'ListSessionEntityTypesRequest', - 'ListSessionEntityTypesResponse', - 'GetSessionEntityTypeRequest', - 'CreateSessionEntityTypeRequest', - 'UpdateSessionEntityTypeRequest', - 'DeleteSessionEntityTypeRequest', - }, -) - - -class SessionEntityType(proto.Message): - r"""Session entity types are referred to as **User** entity types and - are entities that are built for an individual user such as - favorites, preferences, playlists, and so on. - - You can redefine a session entity type at the session level to - extend or replace a [custom entity - type][google.cloud.dialogflow.cx.v3beta1.EntityType] at the user - session level (we refer to the entity types defined at the agent - level as "custom entity types"). - - Note: session entity types apply to all queries, regardless of the - language. - - For more information about entity types, see the `Dialogflow - documentation `__. - - Attributes: - name (str): - Required. The unique identifier of the session entity type. - Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - entity_override_mode (google.cloud.dialogflowcx_v3beta1.types.SessionEntityType.EntityOverrideMode): - Required. Indicates whether the additional - data should override or supplement the custom - entity type definition. - entities (Sequence[google.cloud.dialogflowcx_v3beta1.types.EntityType.Entity]): - Required. The collection of entities to - override or supplement the custom entity type. - """ - class EntityOverrideMode(proto.Enum): - r"""The types of modifications for the 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=3, - enum=EntityOverrideMode, - ) - entities = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=entity_type.EntityType.Entity, - ) - - -class ListSessionEntityTypesRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.ListSessionEntityTypes]. - - Attributes: - parent (str): - Required. The session to list all session entity types from. - Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - 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 ListSessionEntityTypesResponse(proto.Message): - r"""The response message for - [SessionEntityTypes.ListSessionEntityTypes][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.ListSessionEntityTypes]. - - Attributes: - session_entity_types (Sequence[google.cloud.dialogflowcx_v3beta1.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.cx.v3beta1.SessionEntityTypes.GetSessionEntityType]. - - Attributes: - name (str): - Required. The name of the session entity type. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateSessionEntityTypeRequest(proto.Message): - r"""The request message for - [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes.CreateSessionEntityType]. - - Attributes: - parent (str): - Required. The session to create a session entity type for. - Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - session_entity_type (google.cloud.dialogflowcx_v3beta1.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.cx.v3beta1.SessionEntityTypes.UpdateSessionEntityType]. - - Attributes: - session_entity_type (google.cloud.dialogflowcx_v3beta1.types.SessionEntityType): - Required. The session entity type to update. Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - 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.cx.v3beta1.SessionEntityTypes.DeleteSessionEntityType]. - - Attributes: - name (str): - Required. The name of the session entity type to delete. - Format: - ``projects//locations//agents//sessions//entityTypes/`` - or - ``projects//locations//agents//environments//sessions//entityTypes/``. - If ``Environment ID`` is not specified, we assume default - 'draft' environment. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/test_case.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/test_case.py deleted file mode 100644 index 210f2127..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/test_case.py +++ /dev/null @@ -1,1250 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import flow as gcdc_flow -from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page -from google.cloud.dialogflowcx_v3beta1.types import response_message -from google.cloud.dialogflowcx_v3beta1.types import session -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group -from google.protobuf import field_mask_pb2 # 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.cx.v3beta1', - manifest={ - 'TestResult', - 'TestCase', - 'TestCaseResult', - 'TestConfig', - 'ConversationTurn', - 'TestRunDifference', - 'TransitionCoverage', - 'TransitionRouteGroupCoverage', - 'IntentCoverage', - 'CalculateCoverageRequest', - 'CalculateCoverageResponse', - 'ListTestCasesRequest', - 'ListTestCasesResponse', - 'BatchDeleteTestCasesRequest', - 'CreateTestCaseRequest', - 'UpdateTestCaseRequest', - 'GetTestCaseRequest', - 'RunTestCaseRequest', - 'RunTestCaseResponse', - 'RunTestCaseMetadata', - 'BatchRunTestCasesRequest', - 'BatchRunTestCasesResponse', - 'BatchRunTestCasesMetadata', - 'TestError', - 'ImportTestCasesRequest', - 'ImportTestCasesResponse', - 'ImportTestCasesMetadata', - 'TestCaseError', - 'ExportTestCasesRequest', - 'ExportTestCasesResponse', - 'ExportTestCasesMetadata', - 'ListTestCaseResultsRequest', - 'ListTestCaseResultsResponse', - 'GetTestCaseResultRequest', - }, -) - - -class TestResult(proto.Enum): - r"""The test result for a test case and an agent environment.""" - TEST_RESULT_UNSPECIFIED = 0 - PASSED = 1 - FAILED = 2 - - -class TestCase(proto.Message): - r"""Represents a test case. - Attributes: - name (str): - The unique identifier of the test case. - [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.CreateTestCase] - will populate the name automatically. Otherwise use format: - ``projects//locations//agents/ /testCases/``. - tags (Sequence[str]): - Tags are short descriptions that users may - apply to test cases for organizational and - filtering purposes. Each tag should start with - "#" and has a limit of 30 characters. - display_name (str): - Required. The human-readable name of the test - case, unique within the agent. Limit of 200 - characters. - notes (str): - Additional freeform notes about the test - case. Limit of 400 characters. - test_config (google.cloud.dialogflowcx_v3beta1.types.TestConfig): - Config for the test case. - test_case_conversation_turns (Sequence[google.cloud.dialogflowcx_v3beta1.types.ConversationTurn]): - The conversation turns uttered when the test - case was created, in chronological order. These - include the canonical set of agent utterances - that should occur when the agent is working - properly. - creation_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. When the test was created. - last_test_result (google.cloud.dialogflowcx_v3beta1.types.TestCaseResult): - The latest test result. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - tags = proto.RepeatedField( - proto.STRING, - number=2, - ) - display_name = proto.Field( - proto.STRING, - number=3, - ) - notes = proto.Field( - proto.STRING, - number=4, - ) - test_config = proto.Field( - proto.MESSAGE, - number=13, - message='TestConfig', - ) - test_case_conversation_turns = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='ConversationTurn', - ) - creation_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - last_test_result = proto.Field( - proto.MESSAGE, - number=12, - message='TestCaseResult', - ) - - -class TestCaseResult(proto.Message): - r"""Represents a result from running a test case in an agent - environment. - - Attributes: - name (str): - The resource name for the test case result. Format: - ``projects//locations//agents//testCases/ /results/``. - environment (str): - Environment where the test was run. If not - set, it indicates the draft environment. - conversation_turns (Sequence[google.cloud.dialogflowcx_v3beta1.types.ConversationTurn]): - The conversation turns uttered during the - test case replay in chronological order. - test_result (google.cloud.dialogflowcx_v3beta1.types.TestResult): - Whether the test case passed in the agent - environment. - test_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the test was run. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - environment = proto.Field( - proto.STRING, - number=2, - ) - conversation_turns = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='ConversationTurn', - ) - test_result = proto.Field( - proto.ENUM, - number=4, - enum='TestResult', - ) - test_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -class TestConfig(proto.Message): - r"""Represents configurations for a test case. - Attributes: - tracking_parameters (Sequence[str]): - Session parameters to be compared when - calculating differences. - flow (str): - Flow name. If not set, default start flow is assumed. - Format: - ``projects//locations//agents//flows/``. - """ - - tracking_parameters = proto.RepeatedField( - proto.STRING, - number=1, - ) - flow = proto.Field( - proto.STRING, - number=2, - ) - - -class ConversationTurn(proto.Message): - r"""One interaction between a human and virtual agent. The human - provides some input and the virtual agent provides a response. - - Attributes: - user_input (google.cloud.dialogflowcx_v3beta1.types.ConversationTurn.UserInput): - The user input. - virtual_agent_output (google.cloud.dialogflowcx_v3beta1.types.ConversationTurn.VirtualAgentOutput): - The virtual agent output. - """ - - class UserInput(proto.Message): - r"""The input from the human user. - Attributes: - input (google.cloud.dialogflowcx_v3beta1.types.QueryInput): - Supports [text - input][google.cloud.dialogflow.cx.v3beta1.QueryInput.text], - [event - input][google.cloud.dialogflow.cx.v3beta1.QueryInput.event], - [dtmf - input][google.cloud.dialogflow.cx.v3beta1.QueryInput.dtmf] - in the test case. - injected_parameters (google.protobuf.struct_pb2.Struct): - Parameters that need to be injected into the - conversation during intent detection. - is_webhook_enabled (bool): - If webhooks should be allowed to trigger in - response to the user utterance. Often if - parameters are injected, webhooks should not be - enabled. - """ - - input = proto.Field( - proto.MESSAGE, - number=5, - message=session.QueryInput, - ) - injected_parameters = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - is_webhook_enabled = proto.Field( - proto.BOOL, - number=3, - ) - - class VirtualAgentOutput(proto.Message): - r"""The output from the virtual agent. - Attributes: - session_parameters (google.protobuf.struct_pb2.Struct): - The session parameters available to the bot - at this point. - differences (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestRunDifference]): - Output only. If this is part of a [result conversation - turn][TestCaseResult.conversation_turns], the list of - differences between the original run and the replay for this - output, if any. - diagnostic_info (google.protobuf.struct_pb2.Struct): - Required. Input only. The diagnostic - [info][Session.DetectIntentResponse.QueryResult.diagnostic_info] - output for the turn. - triggered_intent (google.cloud.dialogflowcx_v3beta1.types.Intent): - The [Intent][google.cloud.dialogflow.cx.v3beta1.Intent] that - triggered the response. Only name and displayName will be - set. - current_page (google.cloud.dialogflowcx_v3beta1.types.Page): - The [Page][google.cloud.dialogflow.cx.v3beta1.Page] on which - the utterance was spoken. Only name and displayName will be - set. - text_responses (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage.Text]): - The - [text][google.cloud.dialogflow.cx.v3beta1.ResponseMessage.Text] - responses from the agent for the turn. - status (google.rpc.status_pb2.Status): - Response error from the agent in the test - result. If set, other output is empty. - """ - - session_parameters = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - differences = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='TestRunDifference', - ) - diagnostic_info = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - triggered_intent = proto.Field( - proto.MESSAGE, - number=7, - message=gcdc_intent.Intent, - ) - current_page = proto.Field( - proto.MESSAGE, - number=8, - message=gcdc_page.Page, - ) - text_responses = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=response_message.ResponseMessage.Text, - ) - status = proto.Field( - proto.MESSAGE, - number=10, - message=status_pb2.Status, - ) - - user_input = proto.Field( - proto.MESSAGE, - number=1, - message=UserInput, - ) - virtual_agent_output = proto.Field( - proto.MESSAGE, - number=2, - message=VirtualAgentOutput, - ) - - -class TestRunDifference(proto.Message): - r"""The description of differences between original and replayed - agent output. - - Attributes: - type_ (google.cloud.dialogflowcx_v3beta1.types.TestRunDifference.DiffType): - The type of diff. - description (str): - A description of the diff, showing the actual - output vs expected output. - """ - class DiffType(proto.Enum): - r"""What part of the message replay differs from the test case.""" - DIFF_TYPE_UNSPECIFIED = 0 - INTENT = 1 - PAGE = 2 - PARAMETERS = 3 - UTTERANCE = 4 - - type_ = proto.Field( - proto.ENUM, - number=1, - enum=DiffType, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - - -class TransitionCoverage(proto.Message): - r"""Transition coverage represents the percentage of all possible - page transitions (page-level transition routes and event - handlers, excluding transition route groups) present within any - of a parent's test cases. - - Attributes: - transitions (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage.Transition]): - The list of Transitions present in the agent. - coverage_score (float): - The percent of transitions in the agent that - are covered. - """ - - class TransitionNode(proto.Message): - r"""The source or target of a transition. - Attributes: - page (google.cloud.dialogflowcx_v3beta1.types.Page): - Indicates a transition to a - [Page][google.cloud.dialogflow.cx.v3beta1.Page]. Only some - fields such as name and displayname will be set. - flow (google.cloud.dialogflowcx_v3beta1.types.Flow): - Indicates a transition to a - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow]. Only some - fields such as name and displayname will be set. - """ - - page = proto.Field( - proto.MESSAGE, - number=1, - oneof='kind', - message=gcdc_page.Page, - ) - flow = proto.Field( - proto.MESSAGE, - number=2, - oneof='kind', - message=gcdc_flow.Flow, - ) - - class Transition(proto.Message): - r"""A transition in a page. - Attributes: - source (google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage.TransitionNode): - The start node of a transition. - index (int): - The index of a transition in the transition - list. Starting from 0. - target (google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage.TransitionNode): - The end node of a transition. - covered (bool): - Whether or not the transition is covered by - at least one of the agent's test cases. - transition_route (google.cloud.dialogflowcx_v3beta1.types.TransitionRoute): - Intent route or condition route. - event_handler (google.cloud.dialogflowcx_v3beta1.types.EventHandler): - Event handler. - """ - - source = proto.Field( - proto.MESSAGE, - number=1, - message='TransitionCoverage.TransitionNode', - ) - index = proto.Field( - proto.INT32, - number=4, - ) - target = proto.Field( - proto.MESSAGE, - number=2, - message='TransitionCoverage.TransitionNode', - ) - covered = proto.Field( - proto.BOOL, - number=3, - ) - transition_route = proto.Field( - proto.MESSAGE, - number=5, - oneof='detail', - message=gcdc_page.TransitionRoute, - ) - event_handler = proto.Field( - proto.MESSAGE, - number=6, - oneof='detail', - message=gcdc_page.EventHandler, - ) - - transitions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Transition, - ) - coverage_score = proto.Field( - proto.FLOAT, - number=2, - ) - - -class TransitionRouteGroupCoverage(proto.Message): - r"""Transition route group coverage represents the percentage of - all possible transition routes present within any of a parent's - test cases. The results are grouped by the transition route - group. - - Attributes: - coverages (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroupCoverage.Coverage]): - Transition route group coverages. - coverage_score (float): - The percent of transition routes in all the - transition route groups that are covered. - """ - - class Coverage(proto.Message): - r"""Coverage result message for one transition route group. - Attributes: - route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): - Transition route group metadata. Only name - and displayName will be set. - transitions (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroupCoverage.Coverage.Transition]): - The list of transition routes and coverage in - the transition route group. - coverage_score (float): - The percent of transition routes in the - transition route group that are covered. - """ - - class Transition(proto.Message): - r"""A transition coverage in a transition route group. - Attributes: - transition_route (google.cloud.dialogflowcx_v3beta1.types.TransitionRoute): - Intent route or condition route. - covered (bool): - Whether or not the transition route is - covered by at least one of the agent's test - cases. - """ - - transition_route = proto.Field( - proto.MESSAGE, - number=1, - message=gcdc_page.TransitionRoute, - ) - covered = proto.Field( - proto.BOOL, - number=2, - ) - - route_group = proto.Field( - proto.MESSAGE, - number=1, - message=transition_route_group.TransitionRouteGroup, - ) - transitions = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='TransitionRouteGroupCoverage.Coverage.Transition', - ) - coverage_score = proto.Field( - proto.FLOAT, - number=3, - ) - - coverages = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Coverage, - ) - coverage_score = proto.Field( - proto.FLOAT, - number=2, - ) - - -class IntentCoverage(proto.Message): - r"""Intent coverage represents the percentage of all possible - intents in the agent that are triggered in any of a parent's - test cases. - - Attributes: - intents (Sequence[google.cloud.dialogflowcx_v3beta1.types.IntentCoverage.Intent]): - The list of Intents present in the agent - coverage_score (float): - The percent of intents in the agent that are - covered. - """ - - class Intent(proto.Message): - r"""The agent's intent. - Attributes: - intent (str): - The intent full resource name - covered (bool): - Whether or not the intent is covered by at - least one of the agent's test cases. - """ - - intent = proto.Field( - proto.STRING, - number=1, - ) - covered = proto.Field( - proto.BOOL, - number=2, - ) - - intents = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Intent, - ) - coverage_score = proto.Field( - proto.FLOAT, - number=2, - ) - - -class CalculateCoverageRequest(proto.Message): - r"""The request message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. - - Attributes: - agent (str): - Required. The agent to calculate coverage for. Format: - ``projects//locations//agents/``. - type_ (google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageRequest.CoverageType): - Required. The type of coverage requested. - """ - class CoverageType(proto.Enum): - r"""The type of coverage score requested.""" - COVERAGE_TYPE_UNSPECIFIED = 0 - INTENT = 1 - PAGE_TRANSITION = 2 - TRANSITION_ROUTE_GROUP = 3 - - agent = proto.Field( - proto.STRING, - number=3, - ) - type_ = proto.Field( - proto.ENUM, - number=2, - enum=CoverageType, - ) - - -class CalculateCoverageResponse(proto.Message): - r"""The response message for - [TestCases.CalculateCoverage][google.cloud.dialogflow.cx.v3beta1.TestCases.CalculateCoverage]. - - Attributes: - agent (str): - The agent to calculate coverage for. Format: - ``projects//locations//agents/``. - intent_coverage (google.cloud.dialogflowcx_v3beta1.types.IntentCoverage): - Intent coverage. - transition_coverage (google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage): - Transition (excluding transition route - groups) coverage. - route_group_coverage (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroupCoverage): - Transition route group coverage. - """ - - agent = proto.Field( - proto.STRING, - number=5, - ) - intent_coverage = proto.Field( - proto.MESSAGE, - number=2, - oneof='coverage_type', - message='IntentCoverage', - ) - transition_coverage = proto.Field( - proto.MESSAGE, - number=4, - oneof='coverage_type', - message='TransitionCoverage', - ) - route_group_coverage = proto.Field( - proto.MESSAGE, - number=6, - oneof='coverage_type', - message='TransitionRouteGroupCoverage', - ) - - -class ListTestCasesRequest(proto.Message): - r"""The request message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. - - Attributes: - parent (str): - Required. The agent to list all pages for. Format: - ``projects//locations//agents/``. - page_size (int): - The maximum number of items to return in a - single page. By default 20. Note that when - TestCaseView = FULL, the maximum page size - allowed is 20. When TestCaseView = BASIC, the - maximum page size allowed is 500. - page_token (str): - The next_page_token value returned from a previous list - request. - view (google.cloud.dialogflowcx_v3beta1.types.ListTestCasesRequest.TestCaseView): - Specifies whether response should include all - fields or just the metadata. - """ - class TestCaseView(proto.Enum): - r"""Specifies how much test case information to include in the - response. - """ - TEST_CASE_VIEW_UNSPECIFIED = 0 - BASIC = 1 - FULL = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - view = proto.Field( - proto.ENUM, - number=4, - enum=TestCaseView, - ) - - -class ListTestCasesResponse(proto.Message): - r"""The response message for - [TestCases.ListTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCases]. - - Attributes: - test_cases (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestCase]): - The list of test cases. 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 - - test_cases = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TestCase', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class BatchDeleteTestCasesRequest(proto.Message): - r"""The request message for - [TestCases.BatchDeleteTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchDeleteTestCases]. - - Attributes: - parent (str): - Required. The agent to delete test cases from. Format: - ``projects//locations//agents/``. - names (Sequence[str]): - Required. Format of test case names: - ``projects//locations/ /agents//testCases/``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - names = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class CreateTestCaseRequest(proto.Message): - r"""The request message for - [TestCases.CreateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.CreateTestCase]. - - Attributes: - parent (str): - Required. The agent to create the test case for. Format: - ``projects//locations//agents/``. - test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): - Required. The test case to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - test_case = proto.Field( - proto.MESSAGE, - number=2, - message='TestCase', - ) - - -class UpdateTestCaseRequest(proto.Message): - r"""The request message for - [TestCases.UpdateTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.UpdateTestCase]. - - Attributes: - test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): - Required. The test case to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to specify which fields should be - updated. The - [``creationTime``][google.cloud.dialogflow.cx.v3beta1.TestCase.creation_time] - and - [``lastTestResult``][google.cloud.dialogflow.cx.v3beta1.TestCase.last_test_result] - cannot be updated. - """ - - test_case = proto.Field( - proto.MESSAGE, - number=1, - message='TestCase', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetTestCaseRequest(proto.Message): - r"""The request message for - [TestCases.GetTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCase]. - - Attributes: - name (str): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class RunTestCaseRequest(proto.Message): - r"""The request message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. - - Attributes: - name (str): - Required. Format of test case name to run: - ``projects//locations/ /agents//testCases/``. - environment (str): - Optional. Environment name. If not set, draft environment is - assumed. Format: - ``projects//locations//agents//environments/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - environment = proto.Field( - proto.STRING, - number=2, - ) - - -class RunTestCaseResponse(proto.Message): - r"""The response message for - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase]. - - Attributes: - result (google.cloud.dialogflowcx_v3beta1.types.TestCaseResult): - The result. - """ - - result = proto.Field( - proto.MESSAGE, - number=2, - message='TestCaseResult', - ) - - -class RunTestCaseMetadata(proto.Message): - r"""Metadata returned for the - [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase] - long running operation. - """ - - -class BatchRunTestCasesRequest(proto.Message): - r"""The request message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. - - Attributes: - parent (str): - Required. Agent name. Format: - ``projects//locations//agents/ ``. - environment (str): - Optional. If not set, draft environment is assumed. Format: - ``projects//locations//agents//environments/``. - test_cases (Sequence[str]): - Required. Format: - ``projects//locations//agents//testCases/``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - environment = proto.Field( - proto.STRING, - number=2, - ) - test_cases = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class BatchRunTestCasesResponse(proto.Message): - r"""The response message for - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases]. - - Attributes: - results (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestCaseResult]): - The test case results. The detailed [conversation - turns][google.cloud.dialogflow.cx.v3beta1.TestCaseResult.conversation_turns] - are empty in this response. - """ - - results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TestCaseResult', - ) - - -class BatchRunTestCasesMetadata(proto.Message): - r"""Metadata returned for the - [TestCases.BatchRunTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.BatchRunTestCases] - long running operation. - - Attributes: - errors (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestError]): - The test errors. - """ - - errors = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TestError', - ) - - -class TestError(proto.Message): - r"""Error info for running a test. - Attributes: - test_case (str): - The test case resource name. - status (google.rpc.status_pb2.Status): - The status associated with the test. - test_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the test was completed. - """ - - test_case = proto.Field( - proto.STRING, - number=1, - ) - status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - test_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class ImportTestCasesRequest(proto.Message): - r"""The request message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. - - Attributes: - parent (str): - Required. The agent to import test cases to. Format: - ``projects//locations//agents/``. - gcs_uri (str): - The `Google Cloud - Storage `__ URI to - import test cases from. The format of this URI must be - ``gs:///``. - content (bytes): - Uncompressed raw byte content for test cases. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - gcs_uri = proto.Field( - proto.STRING, - number=2, - oneof='source', - ) - content = proto.Field( - proto.BYTES, - number=3, - oneof='source', - ) - - -class ImportTestCasesResponse(proto.Message): - r"""The response message for - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases]. - - Attributes: - names (Sequence[str]): - The unique identifiers of the new test cases. Format: - ``projects//locations//agents//testCases/``. - """ - - names = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class ImportTestCasesMetadata(proto.Message): - r"""Metadata returned for the - [TestCases.ImportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ImportTestCases] - long running operation. - - Attributes: - errors (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestCaseError]): - Errors for failed test cases. - """ - - errors = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TestCaseError', - ) - - -class TestCaseError(proto.Message): - r"""Error info for importing a test. - Attributes: - test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): - The test case. - status (google.rpc.status_pb2.Status): - The status associated with the test case. - """ - - test_case = proto.Field( - proto.MESSAGE, - number=1, - message='TestCase', - ) - status = proto.Field( - proto.MESSAGE, - number=2, - message=status_pb2.Status, - ) - - -class ExportTestCasesRequest(proto.Message): - r"""The request message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. - - Attributes: - parent (str): - Required. The agent where to export test cases from. Format: - ``projects//locations//agents/``. - gcs_uri (str): - The `Google Cloud - Storage `__ URI to - export the test cases to. The format of this URI must be - ``gs:///``. If unspecified, the - serialized test cases is returned inline. - data_format (google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest.DataFormat): - The data format of the exported test cases. If not - specified, ``BLOB`` is assumed. - filter (str): - The filter expression used to filter exported test cases, - see `API Filtering `__. The expression - is case insensitive and supports the following syntax: - - name = [OR name = ] ... - - For example: - - - "name = t1 OR name = t2" matches the test case with the - exact resource name "t1" or "t2". - """ - class DataFormat(proto.Enum): - r"""Data format of the exported test cases.""" - DATA_FORMAT_UNSPECIFIED = 0 - BLOB = 1 - JSON = 2 - - parent = proto.Field( - proto.STRING, - number=1, - ) - gcs_uri = proto.Field( - proto.STRING, - number=2, - oneof='destination', - ) - data_format = proto.Field( - proto.ENUM, - number=3, - enum=DataFormat, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ExportTestCasesResponse(proto.Message): - r"""The response message for - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases]. - - Attributes: - gcs_uri (str): - The URI to a file containing the exported test cases. This - field is populated only if ``gcs_uri`` is specified in - [ExportTestCasesRequest][google.cloud.dialogflow.cx.v3beta1.ExportTestCasesRequest]. - content (bytes): - Uncompressed raw byte content for test cases. - """ - - gcs_uri = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - content = proto.Field( - proto.BYTES, - number=2, - oneof='destination', - ) - - -class ExportTestCasesMetadata(proto.Message): - r"""Metadata returned for the - [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases] - long running operation. - """ - - -class ListTestCaseResultsRequest(proto.Message): - r"""The request message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. - - Attributes: - parent (str): - Required. The test case to list results for. Format: - ``projects//locations//agents// testCases/``. - Specify a ``-`` as a wildcard for TestCase ID to list - results across multiple test cases. - 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. - filter (str): - The filter expression used to filter test case results. See - `API Filtering `__. - - The expression is case insensitive. Only 'AND' is supported - for logical operators. The supported syntax is listed below - in detail: - - [AND ] ... [AND latest] - - The supported fields and operators are: field operator - ``environment`` ``=``, ``IN`` (Use value ``draft`` for draft - environment) ``test_time`` ``>``, ``<`` - - ``latest`` only returns the latest test result in all - results for each test case. - - Examples: - - - "environment=draft AND latest" matches the latest test - result for each test case in the draft environment. - - "environment IN (e1,e2)" matches any test case results - with an environment resource name of either "e1" or "e2". - - "test_time > 1602540713" matches any test case results - with test time later than a unix timestamp in seconds - 1602540713. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - filter = proto.Field( - proto.STRING, - number=4, - ) - - -class ListTestCaseResultsResponse(proto.Message): - r"""The response message for - [TestCases.ListTestCaseResults][google.cloud.dialogflow.cx.v3beta1.TestCases.ListTestCaseResults]. - - Attributes: - test_case_results (Sequence[google.cloud.dialogflowcx_v3beta1.types.TestCaseResult]): - The list of test case results. - 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 - - test_case_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TestCaseResult', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTestCaseResultRequest(proto.Message): - r"""The request message for - [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCaseResult]. - - Attributes: - name (str): - Required. The name of the testcase. Format: - ``projects//locations//agents//testCases//results/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py deleted file mode 100644 index f176ed4c..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py +++ /dev/null @@ -1,307 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import page -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'TransitionRouteGroup', - 'ListTransitionRouteGroupsRequest', - 'ListTransitionRouteGroupsResponse', - 'GetTransitionRouteGroupRequest', - 'CreateTransitionRouteGroupRequest', - 'UpdateTransitionRouteGroupRequest', - 'DeleteTransitionRouteGroupRequest', - }, -) - - -class TransitionRouteGroup(proto.Message): - r"""An TransitionRouteGroup represents a group of - [``TransitionRoutes``][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - to be used by a [Page][google.cloud.dialogflow.cx.v3beta1.Page]. - - Attributes: - name (str): - The unique identifier of the transition route group. - [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.CreateTransitionRouteGroup] - populates the name automatically. Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - display_name (str): - Required. The human-readable name of the transition route - group, unique within the - [Agent][google.cloud.dialogflow.cx.v3beta1.Agent]. The - display name can be no longer than 30 characters. - transition_routes (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRoute]): - Transition routes associated with the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - transition_routes = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=page.TransitionRoute, - ) - - -class ListTransitionRouteGroupsRequest(proto.Message): - r"""The request message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. - - Attributes: - parent (str): - Required. The flow to list all transition route groups for. - Format: - ``projects//locations//agents//flows/``. - 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. - language_code (str): - The language to list transition route groups for. The - following fields are language dependent: - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` - - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_size = proto.Field( - proto.INT32, - number=2, - ) - page_token = proto.Field( - proto.STRING, - number=3, - ) - language_code = proto.Field( - proto.STRING, - number=4, - ) - - -class ListTransitionRouteGroupsResponse(proto.Message): - r"""The response message for - [TransitionRouteGroups.ListTransitionRouteGroups][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.ListTransitionRouteGroups]. - - Attributes: - transition_route_groups (Sequence[google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup]): - The list of transition route groups. There will be a maximum - number of items returned based on the page_size field in the - request. The list may in some cases be empty or contain - fewer entries than page_size even if this isn't the last - page. - 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 - - transition_route_groups = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TransitionRouteGroup', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTransitionRouteGroupRequest(proto.Message): - r"""The request message for - [TransitionRouteGroups.GetTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.GetTransitionRouteGroup]. - - Attributes: - name (str): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. - Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - language_code (str): - The language to retrieve the transition route group for. The - following fields are language dependent: - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` - - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - language_code = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateTransitionRouteGroupRequest(proto.Message): - r"""The request message for - [TransitionRouteGroups.CreateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.CreateTransitionRouteGroup]. - - Attributes: - parent (str): - Required. The flow to create an - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - for. Format: - ``projects//locations//agents//flows/``. - transition_route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): - Required. The transition route group to - create. - language_code (str): - The language of the following fields in - ``TransitionRouteGroup``: - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` - - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - transition_route_group = proto.Field( - proto.MESSAGE, - number=2, - message='TransitionRouteGroup', - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateTransitionRouteGroupRequest(proto.Message): - r"""The request message for - [TransitionRouteGroups.UpdateTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.UpdateTransitionRouteGroup]. - - Attributes: - transition_route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): - Required. The transition route group to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The mask to control which fields get updated. - language_code (str): - The language of the following fields in - ``TransitionRouteGroup``: - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` - - - - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` - - If not specified, the agent's default language is used. - `Many - languages `__ - are supported. Note: languages must be enabled in the agent - before they can be used. - """ - - transition_route_group = proto.Field( - proto.MESSAGE, - number=1, - message='TransitionRouteGroup', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - language_code = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteTransitionRouteGroupRequest(proto.Message): - r"""The request message for - [TransitionRouteGroups.DeleteTransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups.DeleteTransitionRouteGroup]. - - Attributes: - name (str): - Required. The name of the - [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] - to delete. Format: - ``projects//locations//agents//flows//transitionRouteGroups/``. - force (bool): - This field has no effect for transition route group that no - page is using. If the transition route group is referenced - by any page: - - - If ``force`` is set to false, an error will be returned - with message indicating pages that reference the - transition route group. - - If ``force`` is set to true, Dialogflow will remove the - transition route group, as well as any reference to it. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/validation_message.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/validation_message.py deleted file mode 100644 index 73c26538..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/validation_message.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.cx.v3beta1', - manifest={ - 'ValidationMessage', - 'ResourceName', - }, -) - - -class ValidationMessage(proto.Message): - r"""Agent/flow validation message. - Attributes: - resource_type (google.cloud.dialogflowcx_v3beta1.types.ValidationMessage.ResourceType): - The type of the resources where the message - is found. - resources (Sequence[str]): - The names of the resources where the message - is found. - resource_names (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResourceName]): - The resource names of the resources where the - message is found. - severity (google.cloud.dialogflowcx_v3beta1.types.ValidationMessage.Severity): - Indicates the severity of the message. - detail (str): - The message detail. - """ - class ResourceType(proto.Enum): - r"""Resource types.""" - RESOURCE_TYPE_UNSPECIFIED = 0 - AGENT = 1 - INTENT = 2 - INTENT_TRAINING_PHRASE = 8 - INTENT_PARAMETER = 9 - INTENTS = 10 - INTENT_TRAINING_PHRASES = 11 - ENTITY_TYPE = 3 - ENTITY_TYPES = 12 - WEBHOOK = 4 - FLOW = 5 - PAGE = 6 - PAGES = 13 - TRANSITION_ROUTE_GROUP = 7 - - class Severity(proto.Enum): - r"""Severity level.""" - SEVERITY_UNSPECIFIED = 0 - INFO = 1 - WARNING = 2 - ERROR = 3 - - resource_type = proto.Field( - proto.ENUM, - number=1, - enum=ResourceType, - ) - resources = proto.RepeatedField( - proto.STRING, - number=2, - ) - resource_names = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='ResourceName', - ) - severity = proto.Field( - proto.ENUM, - number=3, - enum=Severity, - ) - detail = proto.Field( - proto.STRING, - number=4, - ) - - -class ResourceName(proto.Message): - r"""Resource name and display name. - Attributes: - name (str): - Name. - display_name (str): - Display name. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/version.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/version.py deleted file mode 100644 index a49ea58d..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/version.py +++ /dev/null @@ -1,295 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import flow -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'CreateVersionOperationMetadata', - 'Version', - 'ListVersionsRequest', - 'ListVersionsResponse', - 'GetVersionRequest', - 'CreateVersionRequest', - 'UpdateVersionRequest', - 'DeleteVersionRequest', - 'LoadVersionRequest', - }, -) - - -class CreateVersionOperationMetadata(proto.Message): - r"""Metadata associated with the long running operation for - [Versions.CreateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.CreateVersion]. - - Attributes: - version (str): - Name of the created version. Format: - ``projects//locations//agents//flows//versions/``. - """ - - version = proto.Field( - proto.STRING, - number=1, - ) - - -class Version(proto.Message): - r"""Represents a version of a flow. - Attributes: - name (str): - Format: projects//locations//agents//flows//versions/. - Version ID is a self-increasing number generated - by Dialogflow upon version creation. - display_name (str): - Required. The human-readable name of the - version. Limit of 64 characters. - description (str): - The description of the version. The maximum - length is 500 characters. If exceeded, the - request is rejected. - nlu_settings (google.cloud.dialogflowcx_v3beta1.types.NluSettings): - Output only. The NLU settings of the flow at - version creation. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Create time of the version. - state (google.cloud.dialogflowcx_v3beta1.types.Version.State): - Output only. The state of this version. This - field is read-only and cannot be set by create - and update methods. - """ - class State(proto.Enum): - r"""The state of the version.""" - STATE_UNSPECIFIED = 0 - RUNNING = 1 - SUCCEEDED = 2 - FAILED = 3 - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - nlu_settings = proto.Field( - proto.MESSAGE, - number=4, - message=flow.NluSettings, - ) - create_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - state = proto.Field( - proto.ENUM, - number=6, - enum=State, - ) - - -class ListVersionsRequest(proto.Message): - r"""The request message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.Versions.ListVersions]. - - Attributes: - parent (str): - Required. The - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to list all - versions for. Format: - ``projects//locations//agents//flows/``. - page_size (int): - The maximum number of items to return in a - single page. By default 20 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 ListVersionsResponse(proto.Message): - r"""The response message for - [Versions.ListVersions][google.cloud.dialogflow.cx.v3beta1.Versions.ListVersions]. - - Attributes: - versions (Sequence[google.cloud.dialogflowcx_v3beta1.types.Version]): - A list of versions. There will be a maximum number of items - returned based on the page_size field in the request. The - list may in some cases be empty or contain fewer entries - than page_size even if this isn't the last page. - 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.cx.v3beta1.Versions.GetVersion]. - - Attributes: - name (str): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3beta1.Version]. - Format: - ``projects//locations//agents//flows//versions/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateVersionRequest(proto.Message): - r"""The request message for - [Versions.CreateVersion][google.cloud.dialogflow.cx.v3beta1.Versions.CreateVersion]. - - Attributes: - parent (str): - Required. The - [Flow][google.cloud.dialogflow.cx.v3beta1.Flow] to create an - [Version][google.cloud.dialogflow.cx.v3beta1.Version] for. - Format: - ``projects//locations//agents//flows/``. - version (google.cloud.dialogflowcx_v3beta1.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.cx.v3beta1.Versions.UpdateVersion]. - - Attributes: - version (google.cloud.dialogflowcx_v3beta1.types.Version): - Required. The version to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The mask to control which fields get updated. - Currently only ``description`` and ``display_name`` can be - 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.cx.v3beta1.Versions.DeleteVersion]. - - Attributes: - name (str): - Required. The name of the - [Version][google.cloud.dialogflow.cx.v3beta1.Version] to - delete. Format: - ``projects//locations//agents//flows//versions/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class LoadVersionRequest(proto.Message): - r"""The request message for - [Versions.LoadVersion][google.cloud.dialogflow.cx.v3beta1.Versions.LoadVersion]. - - Attributes: - name (str): - Required. The - [Version][google.cloud.dialogflow.cx.v3beta1.Version] to be - loaded to draft flow. Format: - ``projects//locations//agents//flows//versions/``. - allow_override_agent_resources (bool): - This field is used to prevent accidental overwrite of other - agent resources, which can potentially impact other flow's - behavior. If ``allow_override_agent_resources`` is false, - conflicted agent-level resources will not be overridden - (i.e. intents, entities, webhooks). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - allow_override_agent_resources = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/webhook.py b/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/webhook.py deleted file mode 100644 index 88209a31..00000000 --- a/owl-bot-staging/v3beta1/google/cloud/dialogflowcx_v3beta1/types/webhook.py +++ /dev/null @@ -1,793 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.types import response_message -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.dialogflow.cx.v3beta1', - manifest={ - 'Webhook', - 'ListWebhooksRequest', - 'ListWebhooksResponse', - 'GetWebhookRequest', - 'CreateWebhookRequest', - 'UpdateWebhookRequest', - 'DeleteWebhookRequest', - 'WebhookRequest', - 'WebhookResponse', - 'PageInfo', - 'SessionInfo', - }, -) - - -class Webhook(proto.Message): - r"""Webhooks host the developer's business logic. During a - session, webhooks allow the developer to use the data extracted - by Dialogflow's natural language processing to generate dynamic - responses, validate collected data, or trigger actions on the - backend. - - Attributes: - name (str): - The unique identifier of the webhook. Required for the - [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook] - method. - [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook] - populates the name automatically. Format: - ``projects//locations//agents//webhooks/``. - display_name (str): - Required. The human-readable name of the - webhook, unique within the agent. - generic_web_service (google.cloud.dialogflowcx_v3beta1.types.Webhook.GenericWebService): - Configuration for a generic web service. - service_directory (google.cloud.dialogflowcx_v3beta1.types.Webhook.ServiceDirectoryConfig): - Configuration for a `Service - Directory `__ - service. - timeout (google.protobuf.duration_pb2.Duration): - Webhook execution timeout. Execution is - considered failed if Dialogflow doesn't receive - a response from webhook at the end of the - timeout period. Defaults to 5 seconds, maximum - allowed timeout is 30 seconds. - disabled (bool): - Indicates whether the webhook is disabled. - """ - - class GenericWebService(proto.Message): - r"""Represents configuration for a generic web service. - Attributes: - uri (str): - Required. The webhook 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.dialogflowcx_v3beta1.types.Webhook.GenericWebService.RequestHeadersEntry]): - The HTTP request headers to send together - with webhook requests. - """ - - 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, - ) - - class ServiceDirectoryConfig(proto.Message): - r"""Represents configuration for a `Service - Directory `__ service. - - Attributes: - service (str): - Required. The name of `Service - Directory `__ - service. Format: - ``projects//locations//namespaces//services/``. - ``Location ID`` of the service directory must be the same as - the location of the agent. - generic_web_service (google.cloud.dialogflowcx_v3beta1.types.Webhook.GenericWebService): - Generic Service configuration of this - webhook. - """ - - service = proto.Field( - proto.STRING, - number=1, - ) - generic_web_service = proto.Field( - proto.MESSAGE, - number=2, - message='Webhook.GenericWebService', - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - generic_web_service = proto.Field( - proto.MESSAGE, - number=4, - oneof='webhook', - message=GenericWebService, - ) - service_directory = proto.Field( - proto.MESSAGE, - number=7, - oneof='webhook', - message=ServiceDirectoryConfig, - ) - timeout = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - disabled = proto.Field( - proto.BOOL, - number=5, - ) - - -class ListWebhooksRequest(proto.Message): - r"""The request message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. - - Attributes: - parent (str): - Required. The agent to list all webhooks for. Format: - ``projects//locations//agents/``. - 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 ListWebhooksResponse(proto.Message): - r"""The response message for - [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3beta1.Webhooks.ListWebhooks]. - - Attributes: - webhooks (Sequence[google.cloud.dialogflowcx_v3beta1.types.Webhook]): - The list of webhooks. 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 - - webhooks = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Webhook', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class GetWebhookRequest(proto.Message): - r"""The request message for - [Webhooks.GetWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.GetWebhook]. - - Attributes: - name (str): - Required. The name of the webhook. Format: - ``projects//locations//agents//webhooks/``. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateWebhookRequest(proto.Message): - r"""The request message for - [Webhooks.CreateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.CreateWebhook]. - - Attributes: - parent (str): - Required. The agent to create a webhook for. Format: - ``projects//locations//agents/``. - webhook (google.cloud.dialogflowcx_v3beta1.types.Webhook): - Required. The webhook to create. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - webhook = proto.Field( - proto.MESSAGE, - number=2, - message='Webhook', - ) - - -class UpdateWebhookRequest(proto.Message): - r"""The request message for - [Webhooks.UpdateWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.UpdateWebhook]. - - Attributes: - webhook (google.cloud.dialogflowcx_v3beta1.types.Webhook): - Required. The webhook to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The mask to control which fields get updated. - If the mask is not present, all fields will be - updated. - """ - - webhook = proto.Field( - proto.MESSAGE, - number=1, - message='Webhook', - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteWebhookRequest(proto.Message): - r"""The request message for - [Webhooks.DeleteWebhook][google.cloud.dialogflow.cx.v3beta1.Webhooks.DeleteWebhook]. - - Attributes: - name (str): - Required. The name of the webhook to delete. Format: - ``projects//locations//agents//webhooks/``. - force (bool): - This field has no effect for webhook not being used. For - webhooks that are used by pages/flows/transition route - groups: - - - If ``force`` is set to false, an error will be returned - with message indicating the referenced resources. - - If ``force`` is set to true, Dialogflow will remove the - webhook, as well as any references to the webhook (i.e. - [Webhook][google.cloud.dialogflow.cx.v3beta1.Fulfillment.webhook] - and - [tag][google.cloud.dialogflow.cx.v3beta1.Fulfillment.tag]in - fulfillments that point to this webhook will be removed). - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - force = proto.Field( - proto.BOOL, - number=2, - ) - - -class WebhookRequest(proto.Message): - r"""The request message for a webhook call. The request is sent - as a JSON object and the field names will be presented in camel - cases. - - Attributes: - detect_intent_response_id (str): - Always present. The unique identifier of the - [DetectIntentResponse][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse] - that will be returned to the API caller. - text (str): - If [natural language - text][google.cloud.dialogflow.cx.v3beta1.TextInput] was - provided as input, this field will contain a copy of the - text. - trigger_intent (str): - If an - [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was - provided as input, this field will contain a copy of the - intent identifier. Format: - ``projects//locations//agents//intents/``. - transcript (str): - If [natural language speech - audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was - provided as input, this field will contain the transcript - for the audio. - trigger_event (str): - If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] - was provided as input, this field will contain the name of - the event. - language_code (str): - The language code specified in the [original - request][QueryInput.language_code]. - fulfillment_info (google.cloud.dialogflowcx_v3beta1.types.WebhookRequest.FulfillmentInfo): - Always present. Information about the - fulfillment that triggered this webhook call. - intent_info (google.cloud.dialogflowcx_v3beta1.types.WebhookRequest.IntentInfo): - Information about the last matched intent. - page_info (google.cloud.dialogflowcx_v3beta1.types.PageInfo): - Information about page status. - session_info (google.cloud.dialogflowcx_v3beta1.types.SessionInfo): - Information about session status. - messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage]): - The list of rich message responses to present to the user. - Webhook can choose to append or replace this list in - [WebhookResponse.fulfillment_response][google.cloud.dialogflow.cx.v3beta1.WebhookResponse.fulfillment_response]; - payload (google.protobuf.struct_pb2.Struct): - Custom data set in - [QueryParameters.payload][google.cloud.dialogflow.cx.v3beta1.QueryParameters.payload]. - sentiment_analysis_result (google.cloud.dialogflowcx_v3beta1.types.WebhookRequest.SentimentAnalysisResult): - The sentiment analysis result of the current - user request. The field is filled when sentiment - analysis is configured to be enabled for the - request. - """ - - class FulfillmentInfo(proto.Message): - r"""Represents fulfillment information communicated to the - webhook. - - Attributes: - tag (str): - Always present. The tag used to identify - which fulfillment is being called. - """ - - tag = proto.Field( - proto.STRING, - number=1, - ) - - class IntentInfo(proto.Message): - r"""Represents intent information communicated to the webhook. - Attributes: - last_matched_intent (str): - Always present. The unique identifier of the last matched - [intent][google.cloud.dialogflow.cx.v3beta1.Intent]. Format: - ``projects//locations//agents//intents/``. - display_name (str): - Always present. The display name of the last matched - [intent][google.cloud.dialogflow.cx.v3beta1.Intent]. - parameters (Sequence[google.cloud.dialogflowcx_v3beta1.types.WebhookRequest.IntentInfo.ParametersEntry]): - Parameters identified as a result of intent - matching. This is a map of the name of the - identified parameter to the value of the - parameter identified from the user's utterance. - All parameters defined in the matched intent - that are identified will be surfaced here. - confidence (float): - The confidence of the matched intent. Values - range from 0.0 (completely uncertain) to 1.0 - (completely certain). - """ - - class IntentParameterValue(proto.Message): - r"""Represents a value for an intent parameter. - Attributes: - original_value (str): - Always present. Original text value extracted - from user utterance. - resolved_value (google.protobuf.struct_pb2.Value): - Always present. Structured value for the - parameter extracted from user utterance. - """ - - original_value = proto.Field( - proto.STRING, - number=1, - ) - resolved_value = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - last_matched_intent = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=3, - ) - parameters = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message='WebhookRequest.IntentInfo.IntentParameterValue', - ) - confidence = proto.Field( - proto.FLOAT, - number=4, - ) - - class SentimentAnalysisResult(proto.Message): - r"""Represents the result of sentiment analysis. - 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, - ) - - detect_intent_response_id = proto.Field( - proto.STRING, - number=1, - ) - text = proto.Field( - proto.STRING, - number=10, - oneof='query', - ) - trigger_intent = proto.Field( - proto.STRING, - number=11, - oneof='query', - ) - transcript = proto.Field( - proto.STRING, - number=12, - oneof='query', - ) - trigger_event = proto.Field( - proto.STRING, - number=14, - oneof='query', - ) - language_code = proto.Field( - proto.STRING, - number=15, - ) - fulfillment_info = proto.Field( - proto.MESSAGE, - number=6, - message=FulfillmentInfo, - ) - intent_info = proto.Field( - proto.MESSAGE, - number=3, - message=IntentInfo, - ) - page_info = proto.Field( - proto.MESSAGE, - number=4, - message='PageInfo', - ) - session_info = proto.Field( - proto.MESSAGE, - number=5, - message='SessionInfo', - ) - messages = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=response_message.ResponseMessage, - ) - payload = proto.Field( - proto.MESSAGE, - number=8, - message=struct_pb2.Struct, - ) - sentiment_analysis_result = proto.Field( - proto.MESSAGE, - number=9, - message=SentimentAnalysisResult, - ) - - -class WebhookResponse(proto.Message): - r"""The response message for a webhook call. - Attributes: - fulfillment_response (google.cloud.dialogflowcx_v3beta1.types.WebhookResponse.FulfillmentResponse): - The fulfillment response to send to the user. - This field can be omitted by the webhook if it - does not intend to send any response to the - user. - page_info (google.cloud.dialogflowcx_v3beta1.types.PageInfo): - Information about page status. This field can - be omitted by the webhook if it does not intend - to modify page status. - session_info (google.cloud.dialogflowcx_v3beta1.types.SessionInfo): - Information about session status. This field - can be omitted by the webhook if it does not - intend to modify session status. - payload (google.protobuf.struct_pb2.Struct): - Value to append directly to - [QueryResult.webhook_payloads][google.cloud.dialogflow.cx.v3beta1.QueryResult.webhook_payloads]. - target_page (str): - The target page to transition to. Format: - ``projects//locations//agents//flows//pages/``. - target_flow (str): - The target flow to transition to. Format: - ``projects//locations//agents//flows/``. - """ - - class FulfillmentResponse(proto.Message): - r"""Represents a fulfillment response to the user. - Attributes: - messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage]): - The list of rich message responses to present - to the user. - merge_behavior (google.cloud.dialogflowcx_v3beta1.types.WebhookResponse.FulfillmentResponse.MergeBehavior): - Merge behavior for ``messages``. - """ - class MergeBehavior(proto.Enum): - r"""Defines merge behavior for ``messages``.""" - MERGE_BEHAVIOR_UNSPECIFIED = 0 - APPEND = 1 - REPLACE = 2 - - messages = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=response_message.ResponseMessage, - ) - merge_behavior = proto.Field( - proto.ENUM, - number=2, - enum='WebhookResponse.FulfillmentResponse.MergeBehavior', - ) - - fulfillment_response = proto.Field( - proto.MESSAGE, - number=1, - message=FulfillmentResponse, - ) - page_info = proto.Field( - proto.MESSAGE, - number=2, - message='PageInfo', - ) - session_info = proto.Field( - proto.MESSAGE, - number=3, - message='SessionInfo', - ) - payload = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Struct, - ) - target_page = proto.Field( - proto.STRING, - number=5, - oneof='transition', - ) - target_flow = proto.Field( - proto.STRING, - number=6, - oneof='transition', - ) - - -class PageInfo(proto.Message): - r"""Represents page information communicated to and from the - webhook. - - Attributes: - current_page (str): - Always present for - [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. - Ignored for - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - The unique identifier of the current page. Format: - ``projects//locations//agents//flows//pages/``. - form_info (google.cloud.dialogflowcx_v3beta1.types.PageInfo.FormInfo): - Optional for both - [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] - and - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - Information about the form. - """ - - class FormInfo(proto.Message): - r"""Represents form information. - Attributes: - parameter_info (Sequence[google.cloud.dialogflowcx_v3beta1.types.PageInfo.FormInfo.ParameterInfo]): - Optional for both - [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] - and - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - The parameters contained in the form. Note that the webhook - cannot add or remove any form parameter. - """ - - class ParameterInfo(proto.Message): - r"""Represents parameter information. - Attributes: - display_name (str): - Always present for - [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. - Required for - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - The human-readable name of the parameter, unique within the - form. This field cannot be modified by the webhook. - required (bool): - Optional for both - [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] - and - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - Indicates whether the parameter is required. Optional - parameters will not trigger prompts; however, they are - filled if the user specifies them. Required parameters must - be filled before form filling concludes. - state (google.cloud.dialogflowcx_v3beta1.types.PageInfo.FormInfo.ParameterInfo.ParameterState): - Always present for - [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. - Required for - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - The state of the parameter. This field can be set to - [INVALID][google.cloud.dialogflow.cx.v3beta1.PageInfo.FormInfo.ParameterInfo.ParameterState.INVALID] - by the webhook to invalidate the parameter; other values set - by the webhook will be ignored. - value (google.protobuf.struct_pb2.Value): - Optional for both - [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest] - and - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - The value of the parameter. This field can be set by the - webhook to change the parameter value. - just_collected (bool): - Optional for - [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. - Ignored for - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - Indicates if the parameter value was just collected on the - last conversation turn. - """ - class ParameterState(proto.Enum): - r"""Represents the state of a parameter.""" - PARAMETER_STATE_UNSPECIFIED = 0 - EMPTY = 1 - INVALID = 2 - FILLED = 3 - - display_name = proto.Field( - proto.STRING, - number=1, - ) - required = proto.Field( - proto.BOOL, - number=2, - ) - state = proto.Field( - proto.ENUM, - number=3, - enum='PageInfo.FormInfo.ParameterInfo.ParameterState', - ) - value = proto.Field( - proto.MESSAGE, - number=4, - message=struct_pb2.Value, - ) - just_collected = proto.Field( - proto.BOOL, - number=5, - ) - - parameter_info = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='PageInfo.FormInfo.ParameterInfo', - ) - - current_page = proto.Field( - proto.STRING, - number=1, - ) - form_info = proto.Field( - proto.MESSAGE, - number=3, - message=FormInfo, - ) - - -class SessionInfo(proto.Message): - r"""Represents session information communicated to and from the - webhook. - - Attributes: - session (str): - Always present for - [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. - Ignored for - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - The unique identifier of the - [session][google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest.session]. - This field can be used by the webhook to identify a session. - Format: - ``projects//locations//agents//sessions/`` - or - ``projects//locations//agents//environments//sessions/`` - if environment is specified. - parameters (Sequence[google.cloud.dialogflowcx_v3beta1.types.SessionInfo.ParametersEntry]): - Optional for - [WebhookRequest][google.cloud.dialogflow.cx.v3beta1.WebhookRequest]. - Optional for - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - All parameters collected from forms and intents during the - session. Parameters can be created, updated, or removed by - the webhook. To remove a parameter from the session, the - webhook should explicitly set the parameter value to null in - [WebhookResponse][google.cloud.dialogflow.cx.v3beta1.WebhookResponse]. - The map is keyed by parameters' display names. - """ - - session = proto.Field( - proto.STRING, - number=1, - ) - parameters = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v3beta1/mypy.ini b/owl-bot-staging/v3beta1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v3beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v3beta1/noxfile.py b/owl-bot-staging/v3beta1/noxfile.py deleted file mode 100644 index a1f5d979..00000000 --- a/owl-bot-staging/v3beta1/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/dialogflowcx_v3beta1/', - '--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/v3beta1/scripts/fixup_dialogflowcx_v3beta1_keywords.py b/owl-bot-staging/v3beta1/scripts/fixup_dialogflowcx_v3beta1_keywords.py deleted file mode 100644 index a1485d95..00000000 --- a/owl-bot-staging/v3beta1/scripts/fixup_dialogflowcx_v3beta1_keywords.py +++ /dev/null @@ -1,266 +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 dialogflowcxCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_delete_test_cases': ('parent', 'names', ), - 'batch_run_test_cases': ('parent', 'test_cases', 'environment', ), - 'calculate_coverage': ('agent', 'type_', ), - 'create_agent': ('parent', 'agent', ), - 'create_entity_type': ('parent', 'entity_type', 'language_code', ), - 'create_environment': ('parent', 'environment', ), - 'create_experiment': ('parent', 'experiment', ), - 'create_flow': ('parent', 'flow', 'language_code', ), - 'create_intent': ('parent', 'intent', 'language_code', ), - 'create_page': ('parent', 'page', 'language_code', ), - 'create_security_settings': ('parent', 'security_settings', ), - 'create_session_entity_type': ('parent', 'session_entity_type', ), - 'create_test_case': ('parent', 'test_case', ), - 'create_transition_route_group': ('parent', 'transition_route_group', 'language_code', ), - 'create_version': ('parent', 'version', ), - 'create_webhook': ('parent', 'webhook', ), - 'delete_agent': ('name', ), - 'delete_entity_type': ('name', 'force', ), - 'delete_environment': ('name', ), - 'delete_experiment': ('name', ), - 'delete_flow': ('name', 'force', ), - 'delete_intent': ('name', ), - 'delete_page': ('name', 'force', ), - 'delete_security_settings': ('name', ), - 'delete_session_entity_type': ('name', ), - 'delete_transition_route_group': ('name', 'force', ), - 'delete_version': ('name', ), - 'delete_webhook': ('name', 'force', ), - 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', ), - 'export_agent': ('name', 'agent_uri', 'environment', ), - 'export_flow': ('name', 'flow_uri', 'include_referenced_flows', ), - 'export_test_cases': ('parent', 'gcs_uri', 'data_format', 'filter', ), - 'fulfill_intent': ('match_intent_request', 'match', 'output_audio_config', ), - 'get_agent': ('name', ), - 'get_agent_validation_result': ('name', 'language_code', ), - 'get_entity_type': ('name', 'language_code', ), - 'get_environment': ('name', ), - 'get_experiment': ('name', ), - 'get_flow': ('name', 'language_code', ), - 'get_flow_validation_result': ('name', 'language_code', ), - 'get_intent': ('name', 'language_code', ), - 'get_page': ('name', 'language_code', ), - 'get_security_settings': ('name', ), - 'get_session_entity_type': ('name', ), - 'get_test_case': ('name', ), - 'get_test_case_result': ('name', ), - 'get_transition_route_group': ('name', 'language_code', ), - 'get_version': ('name', ), - 'get_webhook': ('name', ), - 'import_flow': ('parent', 'flow_uri', 'flow_content', 'import_option', ), - 'import_test_cases': ('parent', 'gcs_uri', 'content', ), - 'list_agents': ('parent', 'page_size', 'page_token', ), - 'list_continuous_test_results': ('parent', 'page_size', 'page_token', ), - 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_experiments': ('parent', 'page_size', 'page_token', ), - 'list_flows': ('parent', 'page_size', 'page_token', 'language_code', ), - 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), - 'list_pages': ('parent', 'language_code', 'page_size', 'page_token', ), - 'list_security_settings': ('parent', 'page_size', 'page_token', ), - 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), - 'list_test_case_results': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_test_cases': ('parent', 'page_size', 'page_token', 'view', ), - 'list_transition_route_groups': ('parent', 'page_size', 'page_token', 'language_code', ), - 'list_versions': ('parent', 'page_size', 'page_token', ), - 'list_webhooks': ('parent', 'page_size', 'page_token', ), - 'load_version': ('name', 'allow_override_agent_resources', ), - 'lookup_environment_history': ('name', 'page_size', 'page_token', ), - 'match_intent': ('session', 'query_input', 'query_params', ), - 'restore_agent': ('name', 'agent_uri', 'agent_content', 'restore_option', ), - 'run_continuous_test': ('environment', ), - 'run_test_case': ('name', 'environment', ), - 'start_experiment': ('name', ), - 'stop_experiment': ('name', ), - 'streaming_detect_intent': ('query_input', 'session', 'query_params', 'output_audio_config', ), - 'train_flow': ('name', ), - 'update_agent': ('agent', 'update_mask', ), - 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), - 'update_environment': ('environment', 'update_mask', ), - 'update_experiment': ('experiment', 'update_mask', ), - 'update_flow': ('flow', 'update_mask', 'language_code', ), - 'update_intent': ('intent', 'language_code', 'update_mask', ), - 'update_page': ('page', 'language_code', 'update_mask', ), - 'update_security_settings': ('security_settings', 'update_mask', ), - 'update_session_entity_type': ('session_entity_type', 'update_mask', ), - 'update_test_case': ('test_case', 'update_mask', ), - 'update_transition_route_group': ('transition_route_group', 'update_mask', 'language_code', ), - 'update_version': ('version', 'update_mask', ), - 'update_webhook': ('webhook', 'update_mask', ), - 'validate_agent': ('name', 'language_code', ), - 'validate_flow': ('name', 'language_code', ), - } - - 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=dialogflowcxCallTransformer(), -): - """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 dialogflowcx 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/v3beta1/setup.py b/owl-bot-staging/v3beta1/setup.py deleted file mode 100644 index 18e33869..00000000 --- a/owl-bot-staging/v3beta1/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-dialogflowcx', - 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/v3beta1/tests/__init__.py b/owl-bot-staging/v3beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v3beta1/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/v3beta1/tests/unit/__init__.py b/owl-bot-staging/v3beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v3beta1/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/v3beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v3beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v3beta1/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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/__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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py deleted file mode 100644 index f30d1f1b..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py +++ /dev/null @@ -1,3312 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.agents import AgentsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.agents import AgentsClient -from google.cloud.dialogflowcx_v3beta1.services.agents import pagers -from google.cloud.dialogflowcx_v3beta1.services.agents import transports -from google.cloud.dialogflowcx_v3beta1.services.agents.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.agents.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import agent -from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent -from google.cloud.dialogflowcx_v3beta1.types import flow -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3beta1.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_list_agents(transport: str = 'grpc', request_type=agent.ListAgentsRequest): - 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.list_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.ListAgentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_agents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAgentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_agents_from_dict(): - test_list_agents(request_type=dict) - - -def test_list_agents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AgentsClient( - credentials=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_agents), - '__call__') as call: - client.list_agents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() - - -@pytest.mark.asyncio -async def test_list_agents_async(transport: str = 'grpc_asyncio', request_type=agent.ListAgentsRequest): - 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.list_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_agents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAgentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_agents_async_from_dict(): - await test_list_agents_async(request_type=dict) - - -def test_list_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.ListAgentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_agents), - '__call__') as call: - call.return_value = agent.ListAgentsResponse() - client.list_agents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_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.ListAgentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_agents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse()) - await client.list_agents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_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.list_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.ListAgentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_agents( - parent='parent_value', - ) - - # Establish that the 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_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.list_agents( - agent.ListAgentsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_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.list_agents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.ListAgentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.ListAgentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_list_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.list_agents( - agent.ListAgentsRequest(), - parent='parent_value', - ) - - -def test_list_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.list_agents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.ListAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_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_list_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.list_agents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.ListAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_list_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.list_agents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.ListAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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_list_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.list_agents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - agent.Agent(), - ], - next_page_token='abc', - ), - agent.ListAgentsResponse( - agents=[], - next_page_token='def', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - ], - next_page_token='ghi', - ), - agent.ListAgentsResponse( - agents=[ - agent.Agent(), - agent.Agent(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_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_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( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - ) - response = client.get_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -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( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - )) - response = await client.get_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -@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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_agent), - '__call__') as call: - call.return_value = agent.Agent() - client.get_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) - await client.get_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_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( - 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_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(), - name='name_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( - 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_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(), - name='name_value', - ) - - -def test_create_agent(transport: str = 'grpc', request_type=gcdc_agent.CreateAgentRequest): - 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.create_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - ) - response = client.create_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -def test_create_agent_from_dict(): - test_create_agent(request_type=dict) - - -def test_create_agent_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AgentsClient( - credentials=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_agent), - '__call__') as call: - client.create_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() - - -@pytest.mark.asyncio -async def test_create_agent_async(transport: str = 'grpc_asyncio', request_type=gcdc_agent.CreateAgentRequest): - 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.create_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - )) - response = await client.create_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -@pytest.mark.asyncio -async def test_create_agent_async_from_dict(): - await test_create_agent_async(request_type=dict) - - -def test_create_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 = gcdc_agent.CreateAgentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_agent), - '__call__') as call: - call.return_value = gcdc_agent.Agent() - client.create_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_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 = gcdc_agent.CreateAgentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - await client.create_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_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.create_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_agent( - parent='parent_value', - agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') - - -def test_create_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.create_agent( - gcdc_agent.CreateAgentRequest(), - parent='parent_value', - agent=gcdc_agent.Agent(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_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.create_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_agent( - parent='parent_value', - agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') - - -@pytest.mark.asyncio -async def test_create_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.create_agent( - gcdc_agent.CreateAgentRequest(), - parent='parent_value', - agent=gcdc_agent.Agent(name='name_value'), - ) - - -def test_update_agent(transport: str = 'grpc', request_type=gcdc_agent.UpdateAgentRequest): - 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.update_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - ) - response = client.update_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -def test_update_agent_from_dict(): - test_update_agent(request_type=dict) - - -def test_update_agent_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AgentsClient( - credentials=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_agent), - '__call__') as call: - client.update_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() - - -@pytest.mark.asyncio -async def test_update_agent_async(transport: str = 'grpc_asyncio', request_type=gcdc_agent.UpdateAgentRequest): - 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.update_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent( - name='name_value', - display_name='display_name_value', - default_language_code='default_language_code_value', - supported_language_codes=['supported_language_codes_value'], - time_zone='time_zone_value', - description='description_value', - avatar_uri='avatar_uri_value', - start_flow='start_flow_value', - security_settings='security_settings_value', - enable_stackdriver_logging=True, - enable_spell_correction=True, - )) - response = await client.update_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.default_language_code == 'default_language_code_value' - assert response.supported_language_codes == ['supported_language_codes_value'] - assert response.time_zone == 'time_zone_value' - assert response.description == 'description_value' - assert response.avatar_uri == 'avatar_uri_value' - assert response.start_flow == 'start_flow_value' - assert response.security_settings == 'security_settings_value' - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True - - -@pytest.mark.asyncio -async def test_update_agent_async_from_dict(): - await test_update_agent_async(request_type=dict) - - -def test_update_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 = gcdc_agent.UpdateAgentRequest() - - request.agent.name = 'agent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_agent), - '__call__') as call: - call.return_value = gcdc_agent.Agent() - client.update_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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.name=agent.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_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 = gcdc_agent.UpdateAgentRequest() - - request.agent.name = 'agent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - await client.update_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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.name=agent.name/value', - ) in kw['metadata'] - - -def test_update_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.update_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_agent( - agent=gcdc_agent.Agent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].agent == gcdc_agent.Agent(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_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.update_agent( - gcdc_agent.UpdateAgentRequest(), - agent=gcdc_agent.Agent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_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.update_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_agent.Agent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_agent( - agent=gcdc_agent.Agent(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].agent == gcdc_agent.Agent(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_agent_flattened_error_async(): - client = AgentsAsyncClient( - credentials=ga_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_agent( - gcdc_agent.UpdateAgentRequest(), - agent=gcdc_agent.Agent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_agent), - '__call__') as call: - call.return_value = None - client.delete_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_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( - 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_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(), - name='name_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( - 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_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(), - name='name_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_agent), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_export_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_agent), - '__call__') as call: - call.return_value = 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', - 'name=name/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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_agent), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.restore_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_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.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_agent), - '__call__') as call: - call.return_value = 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', - 'name=name/value', - ) in kw['metadata'] - - -def test_validate_agent(transport: str = 'grpc', request_type=agent.ValidateAgentRequest): - 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.validate_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.AgentValidationResult( - name='name_value', - ) - response = client.validate_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == 'name_value' - - -def test_validate_agent_from_dict(): - test_validate_agent(request_type=dict) - - -def test_validate_agent_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AgentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_agent), - '__call__') as call: - client.validate_agent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() - - -@pytest.mark.asyncio -async def test_validate_agent_async(transport: str = 'grpc_asyncio', request_type=agent.ValidateAgentRequest): - 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.validate_agent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult( - name='name_value', - )) - response = await client.validate_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_validate_agent_async_from_dict(): - await test_validate_agent_async(request_type=dict) - - -def test_validate_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.ValidateAgentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_agent), - '__call__') as call: - call.return_value = agent.AgentValidationResult() - client.validate_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_validate_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.ValidateAgentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_agent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) - await client.validate_agent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_agent_validation_result(transport: str = 'grpc', request_type=agent.GetAgentValidationResultRequest): - 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_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.AgentValidationResult( - name='name_value', - ) - response = client.get_agent_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == 'name_value' - - -def test_get_agent_validation_result_from_dict(): - test_get_agent_validation_result(request_type=dict) - - -def test_get_agent_validation_result_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AgentsClient( - credentials=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_validation_result), - '__call__') as call: - client.get_agent_validation_result() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() - - -@pytest.mark.asyncio -async def test_get_agent_validation_result_async(transport: str = 'grpc_asyncio', request_type=agent.GetAgentValidationResultRequest): - 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_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult( - name='name_value', - )) - response = await client.get_agent_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_agent_validation_result_async_from_dict(): - await test_get_agent_validation_result_async(request_type=dict) - - -def test_get_agent_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.GetAgentValidationResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_agent_validation_result), - '__call__') as call: - call.return_value = agent.AgentValidationResult() - client.get_agent_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_agent_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.GetAgentValidationResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_agent_validation_result), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) - await client.get_agent_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_agent_validation_result_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_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.AgentValidationResult() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_agent_validation_result( - name='name_value', - ) - - # Establish that the 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_agent_validation_result_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_validation_result( - agent.GetAgentValidationResultRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_agent_validation_result_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_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = agent.AgentValidationResult() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.AgentValidationResult()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_agent_validation_result( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_agent_validation_result_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_validation_result( - agent.GetAgentValidationResultRequest(), - name='name_value', - ) - - -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.dialogflowcx_v3beta1.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 = ( - 'list_agents', - 'get_agent', - 'create_agent', - 'update_agent', - 'delete_agent', - 'export_agent', - 'restore_agent', - 'validate_agent', - 'get_agent_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.dialogflowcx_v3beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_agents_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AgentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - 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.dialogflowcx_v3beta1.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" - location = "clam" - agent = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) - actual = AgentsClient.agent_path(project, location, agent) - assert expected == actual - - -def test_parse_agent_path(): - expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - } - path = AgentsClient.agent_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_agent_path(path) - assert expected == actual - -def test_agent_validation_result_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/validationResult".format(project=project, location=location, agent=agent, ) - actual = AgentsClient.agent_validation_result_path(project, location, agent) - assert expected == actual - - -def test_parse_agent_validation_result_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "agent": "abalone", - } - path = AgentsClient.agent_validation_result_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_agent_validation_result_path(path) - assert expected == actual - -def test_environment_path(): - project = "squid" - location = "clam" - agent = "whelk" - environment = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - actual = AgentsClient.environment_path(project, location, agent, environment) - assert expected == actual - - -def test_parse_environment_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "environment": "mussel", - } - path = AgentsClient.environment_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_environment_path(path) - assert expected == actual - -def test_flow_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = AgentsClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "flow": "octopus", - } - path = AgentsClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_flow_path(path) - assert expected == actual - -def test_flow_validation_result_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - flow = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) - actual = AgentsClient.flow_validation_result_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_validation_result_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "flow": "abalone", - } - path = AgentsClient.flow_validation_result_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_flow_validation_result_path(path) - assert expected == actual - -def test_security_settings_path(): - project = "squid" - location = "clam" - security_settings = "whelk" - expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - actual = AgentsClient.security_settings_path(project, location, security_settings) - assert expected == actual - - -def test_parse_security_settings_path(): - expected = { - "project": "octopus", - "location": "oyster", - "security_settings": "nudibranch", - } - path = AgentsClient.security_settings_path(**expected) - - # Check that the path construction is reversible. - actual = AgentsClient.parse_security_settings_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - 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": "mussel", - } - 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 = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = AgentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - 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 = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AgentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - 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 = "squid" - expected = "projects/{project}".format(project=project, ) - actual = AgentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - 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 = "whelk" - location = "octopus" - 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": "oyster", - "location": "nudibranch", - } - 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py deleted file mode 100644 index 40d3eac0..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py +++ /dev/null @@ -1,2418 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.entity_types import EntityTypesAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.entity_types import EntityTypesClient -from google.cloud.dialogflowcx_v3beta1.services.entity_types import pagers -from google.cloud.dialogflowcx_v3beta1.services.entity_types import transports -from google.cloud.dialogflowcx_v3beta1.services.entity_types.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.entity_types.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import entity_type -from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3beta1.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', - ) - - # Establish that the 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_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', - ) - - -@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', - ) - - # Establish that 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_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', - ) - - -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, - redact=True, - ) - response = client.get_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -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, - redact=True, - )) - response = await client.get_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -@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', - ) - - # Establish that the 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_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', - ) - - -@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', - ) - - # Establish that 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_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', - ) - - -def test_create_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - redact=True, - ) - response = client.create_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -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] == gcdc_entity_type.CreateEntityTypeRequest() - - -@pytest.mark.asyncio -async def test_create_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - redact=True, - )) - response = await client.create_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_entity_type( - parent='parent_value', - entity_type=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( - gcdc_entity_type.CreateEntityTypeRequest(), - parent='parent_value', - entity_type=gcdc_entity_type.EntityType(name='name_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 = gcdc_entity_type.EntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( - gcdc_entity_type.CreateEntityTypeRequest(), - parent='parent_value', - entity_type=gcdc_entity_type.EntityType(name='name_value'), - ) - - -def test_update_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - redact=True, - ) - response = client.update_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -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] == gcdc_entity_type.UpdateEntityTypeRequest() - - -@pytest.mark.asyncio -async def test_update_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_entity_type.EntityType( - name='name_value', - display_name='display_name_value', - kind=gcdc_entity_type.EntityType.Kind.KIND_MAP, - auto_expansion_mode=gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, - enable_fuzzy_extraction=True, - redact=True, - )) - response = await client.update_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT - assert response.enable_fuzzy_extraction is True - assert response.redact is True - - -@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_entity_type( - entity_type=gcdc_entity_type.EntityType(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcdc_entity_type.EntityType(name='name_value') - assert args[0].update_mask == field_mask_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( - gcdc_entity_type.UpdateEntityTypeRequest(), - entity_type=gcdc_entity_type.EntityType(name='name_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 = gcdc_entity_type.EntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_entity_type.EntityType(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].entity_type == gcdc_entity_type.EntityType(name='name_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( - gcdc_entity_type.UpdateEntityTypeRequest(), - entity_type=gcdc_entity_type.EntityType(name='name_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_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.dialogflowcx_v3beta1.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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_entity_types_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_entity_types_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - 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.dialogflowcx_v3beta1.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_type_path(): - project = "squid" - location = "clam" - agent = "whelk" - entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - actual = EntityTypesClient.entity_type_path(project, location, agent, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "entity_type": "mussel", - } - 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 = "winkle" - 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": "nautilus", - } - 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 = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = EntityTypesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - 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 = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EntityTypesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - 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 = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = EntityTypesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - 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 = "oyster" - location = "nudibranch" - 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": "cuttlefish", - "location": "mussel", - } - 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py deleted file mode 100644 index 26832174..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py +++ /dev/null @@ -1,3467 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.environments import EnvironmentsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.environments import EnvironmentsClient -from google.cloud.dialogflowcx_v3beta1.services.environments import pagers -from google.cloud.dialogflowcx_v3beta1.services.environments import transports -from google.cloud.dialogflowcx_v3beta1.services.environments.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.environments.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import environment -from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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(): - 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.dialogflowcx_v3beta1.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', - display_name='display_name_value', - description='description_value', - ) - response = client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -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', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@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_get_environment_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.get_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.Environment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_environment( - name='name_value', - ) - - # Establish that the 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_environment_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.get_environment( - environment.GetEnvironmentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_environment_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.get_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.Environment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.Environment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_environment( - 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_environment_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.get_environment( - environment.GetEnvironmentRequest(), - name='name_value', - ) - - -def test_create_environment(transport: str = 'grpc', request_type=gcdc_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 = operations_pb2.Operation(name='operations/spam') - response = client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.CreateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -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] == gcdc_environment.CreateEnvironmentRequest() - - -@pytest.mark.asyncio -async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.CreateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@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 = gcdc_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 = operations_pb2.Operation(name='operations/op') - 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 = gcdc_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(operations_pb2.Operation(name='operations/op')) - 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_create_environment_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.create_environment), - '__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_environment( - parent='parent_value', - environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') - - -def test_create_environment_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.create_environment( - gcdc_environment.CreateEnvironmentRequest(), - parent='parent_value', - environment=gcdc_environment.Environment(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_environment_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.create_environment), - '__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_environment( - parent='parent_value', - environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') - - -@pytest.mark.asyncio -async def test_create_environment_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.create_environment( - gcdc_environment.CreateEnvironmentRequest(), - parent='parent_value', - environment=gcdc_environment.Environment(name='name_value'), - ) - - -def test_update_environment(transport: str = 'grpc', request_type=gcdc_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 = operations_pb2.Operation(name='operations/spam') - response = client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.UpdateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -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] == gcdc_environment.UpdateEnvironmentRequest() - - -@pytest.mark.asyncio -async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.UpdateEnvironmentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@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 = gcdc_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 = operations_pb2.Operation(name='operations/op') - 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 = gcdc_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(operations_pb2.Operation(name='operations/op')) - 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_update_environment_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.update_environment), - '__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_environment( - environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_environment_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.update_environment( - gcdc_environment.UpdateEnvironmentRequest(), - environment=gcdc_environment.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_environment_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.update_environment), - '__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_environment( - environment=gcdc_environment.Environment(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].environment == gcdc_environment.Environment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_environment_flattened_error_async(): - client = EnvironmentsAsyncClient( - credentials=ga_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_environment( - gcdc_environment.UpdateEnvironmentRequest(), - environment=gcdc_environment.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -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_delete_environment_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.delete_environment), - '__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_environment( - 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_environment_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.delete_environment( - environment.DeleteEnvironmentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_environment_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.delete_environment), - '__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_environment( - 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_environment_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.delete_environment( - environment.DeleteEnvironmentRequest(), - name='name_value', - ) - - -def test_lookup_environment_history(transport: str = 'grpc', request_type=environment.LookupEnvironmentHistoryRequest): - 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.lookup_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.LookupEnvironmentHistoryResponse( - next_page_token='next_page_token_value', - ) - response = client.lookup_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.LookupEnvironmentHistoryPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_lookup_environment_history_from_dict(): - test_lookup_environment_history(request_type=dict) - - -def test_lookup_environment_history_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lookup_environment_history), - '__call__') as call: - client.lookup_environment_history() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() - - -@pytest.mark.asyncio -async def test_lookup_environment_history_async(transport: str = 'grpc_asyncio', request_type=environment.LookupEnvironmentHistoryRequest): - 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.lookup_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse( - next_page_token='next_page_token_value', - )) - response = await client.lookup_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.LookupEnvironmentHistoryAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_lookup_environment_history_async_from_dict(): - await test_lookup_environment_history_async(request_type=dict) - - -def test_lookup_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.LookupEnvironmentHistoryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lookup_environment_history), - '__call__') as call: - call.return_value = environment.LookupEnvironmentHistoryResponse() - client.lookup_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_lookup_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.LookupEnvironmentHistoryRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lookup_environment_history), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse()) - await client.lookup_environment_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_lookup_environment_history_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.lookup_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.LookupEnvironmentHistoryResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.lookup_environment_history( - name='name_value', - ) - - # Establish that the 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_lookup_environment_history_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.lookup_environment_history( - environment.LookupEnvironmentHistoryRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_lookup_environment_history_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.lookup_environment_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.LookupEnvironmentHistoryResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.LookupEnvironmentHistoryResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.lookup_environment_history( - 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_lookup_environment_history_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.lookup_environment_history( - environment.LookupEnvironmentHistoryRequest(), - name='name_value', - ) - - -def test_lookup_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.lookup_environment_history), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[], - next_page_token='def', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', ''), - )), - ) - pager = client.lookup_environment_history(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_lookup_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.lookup_environment_history), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[], - next_page_token='def', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - pages = list(client.lookup_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_lookup_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.lookup_environment_history), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[], - next_page_token='def', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - async_pager = await client.lookup_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.Environment) - for i in responses) - -@pytest.mark.asyncio -async def test_lookup_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.lookup_environment_history), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - environment.Environment(), - ], - next_page_token='abc', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[], - next_page_token='def', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - ], - next_page_token='ghi', - ), - environment.LookupEnvironmentHistoryResponse( - environments=[ - environment.Environment(), - environment.Environment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.lookup_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_run_continuous_test(transport: str = 'grpc', request_type=environment.RunContinuousTestRequest): - 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.run_continuous_test), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_continuous_test(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.RunContinuousTestRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_continuous_test_from_dict(): - test_run_continuous_test(request_type=dict) - - -def test_run_continuous_test_empty_call(): - # 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.run_continuous_test), - '__call__') as call: - client.run_continuous_test() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.RunContinuousTestRequest() - - -@pytest.mark.asyncio -async def test_run_continuous_test_async(transport: str = 'grpc_asyncio', request_type=environment.RunContinuousTestRequest): - 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.run_continuous_test), - '__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.run_continuous_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.RunContinuousTestRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_run_continuous_test_async_from_dict(): - await test_run_continuous_test_async(request_type=dict) - - -def test_run_continuous_test_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.RunContinuousTestRequest() - - request.environment = 'environment/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_continuous_test), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_continuous_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=environment/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_run_continuous_test_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.RunContinuousTestRequest() - - request.environment = 'environment/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_continuous_test), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_continuous_test(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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=environment/value', - ) in kw['metadata'] - - -def test_list_continuous_test_results(transport: str = 'grpc', request_type=environment.ListContinuousTestResultsRequest): - 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_continuous_test_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.ListContinuousTestResultsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_continuous_test_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListContinuousTestResultsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListContinuousTestResultsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_continuous_test_results_from_dict(): - test_list_continuous_test_results(request_type=dict) - - -def test_list_continuous_test_results_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = 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_continuous_test_results), - '__call__') as call: - client.list_continuous_test_results() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListContinuousTestResultsRequest() - - -@pytest.mark.asyncio -async def test_list_continuous_test_results_async(transport: str = 'grpc_asyncio', request_type=environment.ListContinuousTestResultsRequest): - 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_continuous_test_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environment.ListContinuousTestResultsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_continuous_test_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListContinuousTestResultsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListContinuousTestResultsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_continuous_test_results_async_from_dict(): - await test_list_continuous_test_results_async(request_type=dict) - - -def test_list_continuous_test_results_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.ListContinuousTestResultsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_continuous_test_results), - '__call__') as call: - call.return_value = environment.ListContinuousTestResultsResponse() - client.list_continuous_test_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_continuous_test_results_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.ListContinuousTestResultsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_continuous_test_results), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListContinuousTestResultsResponse()) - await client.list_continuous_test_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_continuous_test_results_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_continuous_test_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.ListContinuousTestResultsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_continuous_test_results( - 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_continuous_test_results_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_continuous_test_results( - environment.ListContinuousTestResultsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_continuous_test_results_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_continuous_test_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environment.ListContinuousTestResultsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environment.ListContinuousTestResultsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_continuous_test_results( - 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_continuous_test_results_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_continuous_test_results( - environment.ListContinuousTestResultsRequest(), - parent='parent_value', - ) - - -def test_list_continuous_test_results_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_continuous_test_results), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - ], - next_page_token='abc', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[], - next_page_token='def', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - ], - next_page_token='ghi', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_continuous_test_results(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, environment.ContinuousTestResult) - for i in results) - -def test_list_continuous_test_results_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_continuous_test_results), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - ], - next_page_token='abc', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[], - next_page_token='def', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - ], - next_page_token='ghi', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_continuous_test_results(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_continuous_test_results_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_continuous_test_results), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - ], - next_page_token='abc', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[], - next_page_token='def', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - ], - next_page_token='ghi', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_continuous_test_results(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.ContinuousTestResult) - for i in responses) - -@pytest.mark.asyncio -async def test_list_continuous_test_results_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_continuous_test_results), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - ], - next_page_token='abc', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[], - next_page_token='def', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - ], - next_page_token='ghi', - ), - environment.ListContinuousTestResultsResponse( - continuous_test_results=[ - environment.ContinuousTestResult(), - environment.ContinuousTestResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_continuous_test_results(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.dialogflowcx_v3beta1.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', - 'lookup_environment_history', - 'run_continuous_test', - 'list_continuous_test_results', - ) - 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_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.dialogflowcx_v3beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_environments_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (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.dialogflowcx_v3beta1.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_environments_grpc_lro_client(): - client = EnvironmentsClient( - 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_environments_grpc_lro_async_client(): - client = EnvironmentsAsyncClient( - 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_continuous_test_result_path(): - project = "squid" - location = "clam" - agent = "whelk" - environment = "octopus" - continuous_test_result = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/continuousTestResults/{continuous_test_result}".format(project=project, location=location, agent=agent, environment=environment, continuous_test_result=continuous_test_result, ) - actual = EnvironmentsClient.continuous_test_result_path(project, location, agent, environment, continuous_test_result) - assert expected == actual - - -def test_parse_continuous_test_result_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "environment": "winkle", - "continuous_test_result": "nautilus", - } - path = EnvironmentsClient.continuous_test_result_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_continuous_test_result_path(path) - assert expected == actual - -def test_environment_path(): - project = "scallop" - location = "abalone" - agent = "squid" - environment = "clam" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - actual = EnvironmentsClient.environment_path(project, location, agent, environment) - assert expected == actual - - -def test_parse_environment_path(): - expected = { - "project": "whelk", - "location": "octopus", - "agent": "oyster", - "environment": "nudibranch", - } - path = EnvironmentsClient.environment_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_environment_path(path) - assert expected == actual - -def test_test_case_result_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - test_case = "nautilus" - result = "scallop" - expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) - actual = EnvironmentsClient.test_case_result_path(project, location, agent, test_case, result) - assert expected == actual - - -def test_parse_test_case_result_path(): - expected = { - "project": "abalone", - "location": "squid", - "agent": "clam", - "test_case": "whelk", - "result": "octopus", - } - path = EnvironmentsClient.test_case_result_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_test_case_result_path(path) - assert expected == actual - -def test_version_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - flow = "mussel" - version = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - actual = EnvironmentsClient.version_path(project, location, agent, flow, version) - assert expected == actual - - -def test_parse_version_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "agent": "abalone", - "flow": "squid", - "version": "clam", - } - path = EnvironmentsClient.version_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_version_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - 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": "octopus", - } - 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 = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - 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 = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - 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 = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - 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 = "scallop" - location = "abalone" - 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": "squid", - "location": "clam", - } - 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py deleted file mode 100644 index 0b79898a..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py +++ /dev/null @@ -1,2911 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.experiments import ExperimentsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.experiments import ExperimentsClient -from google.cloud.dialogflowcx_v3beta1.services.experiments import pagers -from google.cloud.dialogflowcx_v3beta1.services.experiments import transports -from google.cloud.dialogflowcx_v3beta1.services.experiments.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.experiments.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import experiment -from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # 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(): - 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 ExperimentsClient._get_default_mtls_endpoint(None) is None - assert ExperimentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ExperimentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ExperimentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ExperimentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ExperimentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - ExperimentsClient, - ExperimentsAsyncClient, -]) -def test_experiments_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", [ - ExperimentsClient, - ExperimentsAsyncClient, -]) -def test_experiments_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_experiments_client_get_transport_class(): - transport = ExperimentsClient.get_transport_class() - available_transports = [ - transports.ExperimentsGrpcTransport, - ] - assert transport in available_transports - - transport = ExperimentsClient.get_transport_class("grpc") - assert transport == transports.ExperimentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), - (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient)) -@mock.patch.object(ExperimentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsAsyncClient)) -def test_experiments_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(ExperimentsClient, '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(ExperimentsClient, '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", [ - (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "true"), - (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc", "false"), - (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(ExperimentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsClient)) -@mock.patch.object(ExperimentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ExperimentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_experiments_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", [ - (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), - (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_experiments_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", [ - (ExperimentsClient, transports.ExperimentsGrpcTransport, "grpc"), - (ExperimentsAsyncClient, transports.ExperimentsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_experiments_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_experiments_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ExperimentsClient( - 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_experiments(transport: str = 'grpc', request_type=experiment.ListExperimentsRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.ListExperimentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_experiments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExperimentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_experiments_from_dict(): - test_list_experiments(request_type=dict) - - -def test_list_experiments_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=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_experiments), - '__call__') as call: - client.list_experiments() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() - - -@pytest.mark.asyncio -async def test_list_experiments_async(transport: str = 'grpc_asyncio', request_type=experiment.ListExperimentsRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_experiments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExperimentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_experiments_async_from_dict(): - await test_list_experiments_async(request_type=dict) - - -def test_list_experiments_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.ListExperimentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - call.return_value = experiment.ListExperimentsResponse() - client.list_experiments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_experiments_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.ListExperimentsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse()) - await client.list_experiments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_experiments_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.ListExperimentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_experiments( - parent='parent_value', - ) - - # Establish that the 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_experiments_flattened_error(): - client = ExperimentsClient( - credentials=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_experiments( - experiment.ListExperimentsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_experiments_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.ListExperimentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.ListExperimentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_experiments( - 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_experiments_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_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_experiments( - experiment.ListExperimentsRequest(), - parent='parent_value', - ) - - -def test_list_experiments_pager(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - experiment.Experiment(), - ], - next_page_token='abc', - ), - experiment.ListExperimentsResponse( - experiments=[], - next_page_token='def', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - ], - next_page_token='ghi', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_experiments(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, experiment.Experiment) - for i in results) - -def test_list_experiments_pages(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - experiment.Experiment(), - ], - next_page_token='abc', - ), - experiment.ListExperimentsResponse( - experiments=[], - next_page_token='def', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - ], - next_page_token='ghi', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_experiments(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_experiments_async_pager(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - experiment.Experiment(), - ], - next_page_token='abc', - ), - experiment.ListExperimentsResponse( - experiments=[], - next_page_token='def', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - ], - next_page_token='ghi', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_experiments(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, experiment.Experiment) - for i in responses) - -@pytest.mark.asyncio -async def test_list_experiments_async_pages(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_experiments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - experiment.Experiment(), - ], - next_page_token='abc', - ), - experiment.ListExperimentsResponse( - experiments=[], - next_page_token='def', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - ], - next_page_token='ghi', - ), - experiment.ListExperimentsResponse( - experiments=[ - experiment.Experiment(), - experiment.Experiment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_experiments(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_experiment(transport: str = 'grpc', request_type=experiment.GetExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - ) - response = client.get_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -def test_get_experiment_from_dict(): - test_get_experiment(request_type=dict) - - -def test_get_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=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_experiment), - '__call__') as call: - client.get_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() - - -@pytest.mark.asyncio -async def test_get_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.GetExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - )) - response = await client.get_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -@pytest.mark.asyncio -async def test_get_experiment_async_from_dict(): - await test_get_experiment_async(request_type=dict) - - -def test_get_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.GetExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_experiment), - '__call__') as call: - call.return_value = experiment.Experiment() - client.get_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.GetExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - await client.get_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_experiment( - name='name_value', - ) - - # Establish that the 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_experiment_flattened_error(): - client = ExperimentsClient( - credentials=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_experiment( - experiment.GetExperimentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_experiment( - 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_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_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_experiment( - experiment.GetExperimentRequest(), - name='name_value', - ) - - -def test_create_experiment(transport: str = 'grpc', request_type=gcdc_experiment.CreateExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_experiment.Experiment.State.DRAFT, - ) - response = client.create_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_experiment.Experiment.State.DRAFT - - -def test_create_experiment_from_dict(): - test_create_experiment(request_type=dict) - - -def test_create_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=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_experiment), - '__call__') as call: - client.create_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() - - -@pytest.mark.asyncio -async def test_create_experiment_async(transport: str = 'grpc_asyncio', request_type=gcdc_experiment.CreateExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_experiment.Experiment.State.DRAFT, - )) - response = await client.create_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_experiment.Experiment.State.DRAFT - - -@pytest.mark.asyncio -async def test_create_experiment_async_from_dict(): - await test_create_experiment_async(request_type=dict) - - -def test_create_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_experiment.CreateExperimentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_experiment), - '__call__') as call: - call.return_value = gcdc_experiment.Experiment() - client.create_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_experiment.CreateExperimentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) - await client.create_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_experiment( - parent='parent_value', - experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') - - -def test_create_experiment_flattened_error(): - client = ExperimentsClient( - credentials=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_experiment( - gcdc_experiment.CreateExperimentRequest(), - parent='parent_value', - experiment=gcdc_experiment.Experiment(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_experiment( - parent='parent_value', - experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') - - -@pytest.mark.asyncio -async def test_create_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_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_experiment( - gcdc_experiment.CreateExperimentRequest(), - parent='parent_value', - experiment=gcdc_experiment.Experiment(name='name_value'), - ) - - -def test_update_experiment(transport: str = 'grpc', request_type=gcdc_experiment.UpdateExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_experiment.Experiment.State.DRAFT, - ) - response = client.update_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_experiment.Experiment.State.DRAFT - - -def test_update_experiment_from_dict(): - test_update_experiment(request_type=dict) - - -def test_update_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=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_experiment), - '__call__') as call: - client.update_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() - - -@pytest.mark.asyncio -async def test_update_experiment_async(transport: str = 'grpc_asyncio', request_type=gcdc_experiment.UpdateExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_experiment.Experiment.State.DRAFT, - )) - response = await client.update_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_experiment.Experiment.State.DRAFT - - -@pytest.mark.asyncio -async def test_update_experiment_async_from_dict(): - await test_update_experiment_async(request_type=dict) - - -def test_update_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_experiment.UpdateExperimentRequest() - - request.experiment.name = 'experiment.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_experiment), - '__call__') as call: - call.return_value = gcdc_experiment.Experiment() - client.update_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'experiment.name=experiment.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_experiment.UpdateExperimentRequest() - - request.experiment.name = 'experiment.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) - await client.update_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'experiment.name=experiment.name/value', - ) in kw['metadata'] - - -def test_update_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_experiment( - experiment=gcdc_experiment.Experiment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].experiment == gcdc_experiment.Experiment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_experiment_flattened_error(): - client = ExperimentsClient( - credentials=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_experiment( - gcdc_experiment.UpdateExperimentRequest(), - experiment=gcdc_experiment.Experiment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_experiment.Experiment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_experiment.Experiment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_experiment( - experiment=gcdc_experiment.Experiment(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].experiment == gcdc_experiment.Experiment(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_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_experiment( - gcdc_experiment.UpdateExperimentRequest(), - experiment=gcdc_experiment.Experiment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_experiment(transport: str = 'grpc', request_type=experiment.DeleteExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_experiment_from_dict(): - test_delete_experiment(request_type=dict) - - -def test_delete_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=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_experiment), - '__call__') as call: - client.delete_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() - - -@pytest.mark.asyncio -async def test_delete_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.DeleteExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_experiment_async_from_dict(): - await test_delete_experiment_async(request_type=dict) - - -def test_delete_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.DeleteExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_experiment), - '__call__') as call: - call.return_value = None - client.delete_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.DeleteExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_experiment), - '__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_experiment( - 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_experiment_flattened_error(): - client = ExperimentsClient( - credentials=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_experiment( - experiment.DeleteExperimentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_experiment), - '__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_experiment( - 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_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_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_experiment( - experiment.DeleteExperimentRequest(), - name='name_value', - ) - - -def test_start_experiment(transport: str = 'grpc', request_type=experiment.StartExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - ) - response = client.start_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -def test_start_experiment_from_dict(): - test_start_experiment(request_type=dict) - - -def test_start_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - client.start_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() - - -@pytest.mark.asyncio -async def test_start_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.StartExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - )) - response = await client.start_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -@pytest.mark.asyncio -async def test_start_experiment_async_from_dict(): - await test_start_experiment_async(request_type=dict) - - -def test_start_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.StartExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - call.return_value = experiment.Experiment() - client.start_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.StartExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - await client.start_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_start_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.start_experiment( - name='name_value', - ) - - # Establish that the 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_start_experiment_flattened_error(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.start_experiment( - experiment.StartExperimentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_start_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.start_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.start_experiment( - 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_start_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.start_experiment( - experiment.StartExperimentRequest(), - name='name_value', - ) - - -def test_stop_experiment(transport: str = 'grpc', request_type=experiment.StopExperimentRequest): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - ) - response = client.stop_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -def test_stop_experiment_from_dict(): - test_stop_experiment(request_type=dict) - - -def test_stop_experiment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - client.stop_experiment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() - - -@pytest.mark.asyncio -async def test_stop_experiment_async(transport: str = 'grpc_asyncio', request_type=experiment.StopExperimentRequest): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment( - name='name_value', - display_name='display_name_value', - description='description_value', - state=experiment.Experiment.State.DRAFT, - )) - response = await client.stop_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == experiment.Experiment.State.DRAFT - - -@pytest.mark.asyncio -async def test_stop_experiment_async_from_dict(): - await test_stop_experiment_async(request_type=dict) - - -def test_stop_experiment_field_headers(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.StopExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - call.return_value = experiment.Experiment() - client.stop_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_experiment_field_headers_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = experiment.StopExperimentRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - await client.stop_experiment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_stop_experiment_flattened(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.stop_experiment( - name='name_value', - ) - - # Establish that the 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_stop_experiment_flattened_error(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.stop_experiment( - experiment.StopExperimentRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_stop_experiment_flattened_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_experiment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = experiment.Experiment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(experiment.Experiment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.stop_experiment( - 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_stop_experiment_flattened_error_async(): - client = ExperimentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.stop_experiment( - experiment.StopExperimentRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ExperimentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ExperimentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExperimentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ExperimentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ExperimentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ExperimentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ExperimentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ExperimentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ExperimentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ExperimentsGrpcTransport, - transports.ExperimentsGrpcAsyncIOTransport, -]) -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 = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ExperimentsGrpcTransport, - ) - -def test_experiments_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ExperimentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_experiments_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ExperimentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_experiments', - 'get_experiment', - 'create_experiment', - 'update_experiment', - 'delete_experiment', - 'start_experiment', - 'stop_experiment', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_experiments_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExperimentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_experiments_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExperimentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_experiments_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ExperimentsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_experiments_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ExperimentsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_experiments_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - ExperimentsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ExperimentsGrpcTransport, - transports.ExperimentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_experiments_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ExperimentsGrpcTransport, - transports.ExperimentsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_experiments_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ExperimentsGrpcTransport, grpc_helpers), - (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_experiments_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ExperimentsGrpcTransport, grpc_helpers), - (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_experiments_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ExperimentsGrpcTransport, grpc_helpers), - (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_experiments_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) -def test_experiments_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = 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_experiments_host_no_port(): - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_experiments_host_with_port(): - client = ExperimentsClient( - 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_experiments_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ExperimentsGrpcTransport( - 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_experiments_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ExperimentsGrpcAsyncIOTransport( - 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.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) -def test_experiments_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.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport]) -def test_experiments_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_experiment_path(): - project = "squid" - location = "clam" - agent = "whelk" - environment = "octopus" - experiment = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format(project=project, location=location, agent=agent, environment=environment, experiment=experiment, ) - actual = ExperimentsClient.experiment_path(project, location, agent, environment, experiment) - assert expected == actual - - -def test_parse_experiment_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "environment": "winkle", - "experiment": "nautilus", - } - path = ExperimentsClient.experiment_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.parse_experiment_path(path) - assert expected == actual - -def test_version_path(): - project = "scallop" - location = "abalone" - agent = "squid" - flow = "clam" - version = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - actual = ExperimentsClient.version_path(project, location, agent, flow, version) - assert expected == actual - - -def test_parse_version_path(): - expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - "flow": "cuttlefish", - "version": "mussel", - } - path = ExperimentsClient.version_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.parse_version_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ExperimentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = ExperimentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = ExperimentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = ExperimentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ExperimentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = ExperimentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = ExperimentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = ExperimentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.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 = ExperimentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = ExperimentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ExperimentsClient.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.ExperimentsTransport, '_prep_wrapped_messages') as prep: - client = ExperimentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ExperimentsTransport, '_prep_wrapped_messages') as prep: - transport_class = ExperimentsClient.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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py deleted file mode 100644 index bfc8cd15..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py +++ /dev/null @@ -1,3472 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.flows import FlowsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.flows import FlowsClient -from google.cloud.dialogflowcx_v3beta1.services.flows import pagers -from google.cloud.dialogflowcx_v3beta1.services.flows import transports -from google.cloud.dialogflowcx_v3beta1.services.flows.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.flows.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import flow -from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow -from google.cloud.dialogflowcx_v3beta1.types import fulfillment -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import response_message -from google.cloud.dialogflowcx_v3beta1.types import validation_message -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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(): - 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 FlowsClient._get_default_mtls_endpoint(None) is None - assert FlowsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert FlowsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert FlowsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert FlowsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert FlowsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - FlowsClient, - FlowsAsyncClient, -]) -def test_flows_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", [ - FlowsClient, - FlowsAsyncClient, -]) -def test_flows_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_flows_client_get_transport_class(): - transport = FlowsClient.get_transport_class() - available_transports = [ - transports.FlowsGrpcTransport, - ] - assert transport in available_transports - - transport = FlowsClient.get_transport_class("grpc") - assert transport == transports.FlowsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (FlowsClient, transports.FlowsGrpcTransport, "grpc"), - (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(FlowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsClient)) -@mock.patch.object(FlowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsAsyncClient)) -def test_flows_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(FlowsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=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(FlowsClient, '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", [ - (FlowsClient, transports.FlowsGrpcTransport, "grpc", "true"), - (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (FlowsClient, transports.FlowsGrpcTransport, "grpc", "false"), - (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(FlowsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsClient)) -@mock.patch.object(FlowsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FlowsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_flows_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", [ - (FlowsClient, transports.FlowsGrpcTransport, "grpc"), - (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_flows_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", [ - (FlowsClient, transports.FlowsGrpcTransport, "grpc"), - (FlowsAsyncClient, transports.FlowsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_flows_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_flows_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = FlowsClient( - 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_flow(transport: str = 'grpc', request_type=gcdc_flow.CreateFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.create_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_create_flow_from_dict(): - test_create_flow(request_type=dict) - - -def test_create_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow), - '__call__') as call: - client.create_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() - - -@pytest.mark.asyncio -async def test_create_flow_async(transport: str = 'grpc_asyncio', request_type=gcdc_flow.CreateFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.create_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_create_flow_async_from_dict(): - await test_create_flow_async(request_type=dict) - - -def test_create_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_flow.CreateFlowRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - call.return_value = gcdc_flow.Flow() - client.create_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_flow.CreateFlowRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - await client.create_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_flow_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_flow( - parent='parent_value', - flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') - - -def test_create_flow_flattened_error(): - client = FlowsClient( - credentials=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_flow( - gcdc_flow.CreateFlowRequest(), - parent='parent_value', - flow=gcdc_flow.Flow(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_flow_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_flow( - parent='parent_value', - flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') - - -@pytest.mark.asyncio -async def test_create_flow_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow( - gcdc_flow.CreateFlowRequest(), - parent='parent_value', - flow=gcdc_flow.Flow(name='name_value'), - ) - - -def test_delete_flow(transport: str = 'grpc', request_type=flow.DeleteFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_flow_from_dict(): - test_delete_flow(request_type=dict) - - -def test_delete_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow), - '__call__') as call: - client.delete_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() - - -@pytest.mark.asyncio -async def test_delete_flow_async(transport: str = 'grpc_asyncio', request_type=flow.DeleteFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_flow_async_from_dict(): - await test_delete_flow_async(request_type=dict) - - -def test_delete_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.DeleteFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - call.return_value = None - client.delete_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.DeleteFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_flow( - name='name_value', - ) - - # Establish that the 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_flow_flattened_error(): - client = FlowsClient( - credentials=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_flow( - flow.DeleteFlowRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_flow_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_flow), - '__call__') as call: - # 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_flow( - 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_flow_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow( - flow.DeleteFlowRequest(), - name='name_value', - ) - - -def test_list_flows(transport: str = 'grpc', request_type=flow.ListFlowsRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.ListFlowsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_flows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFlowsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_flows_from_dict(): - test_list_flows(request_type=dict) - - -def test_list_flows_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flows), - '__call__') as call: - client.list_flows() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() - - -@pytest.mark.asyncio -async def test_list_flows_async(transport: str = 'grpc_asyncio', request_type=flow.ListFlowsRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_flows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFlowsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_flows_async_from_dict(): - await test_list_flows_async(request_type=dict) - - -def test_list_flows_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ListFlowsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - call.return_value = flow.ListFlowsResponse() - client.list_flows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_flows_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ListFlowsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse()) - await client.list_flows(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_flows_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.ListFlowsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_flows( - parent='parent_value', - ) - - # Establish that the 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_flows_flattened_error(): - client = FlowsClient( - credentials=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_flows( - flow.ListFlowsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_flows_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.ListFlowsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.ListFlowsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_flows( - 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_flows_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flows( - flow.ListFlowsRequest(), - parent='parent_value', - ) - - -def test_list_flows_pager(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - flow.Flow(), - ], - next_page_token='abc', - ), - flow.ListFlowsResponse( - flows=[], - next_page_token='def', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - ], - next_page_token='ghi', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_flows(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, flow.Flow) - for i in results) - -def test_list_flows_pages(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - flow.Flow(), - ], - next_page_token='abc', - ), - flow.ListFlowsResponse( - flows=[], - next_page_token='def', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - ], - next_page_token='ghi', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - ], - ), - RuntimeError, - ) - pages = list(client.list_flows(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_flows_async_pager(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - flow.Flow(), - ], - next_page_token='abc', - ), - flow.ListFlowsResponse( - flows=[], - next_page_token='def', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - ], - next_page_token='ghi', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_flows(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, flow.Flow) - for i in responses) - -@pytest.mark.asyncio -async def test_list_flows_async_pages(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_flows), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - flow.Flow(), - ], - next_page_token='abc', - ), - flow.ListFlowsResponse( - flows=[], - next_page_token='def', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - ], - next_page_token='ghi', - ), - flow.ListFlowsResponse( - flows=[ - flow.Flow(), - flow.Flow(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_flows(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_flow(transport: str = 'grpc', request_type=flow.GetFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.get_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_get_flow_from_dict(): - test_get_flow(request_type=dict) - - -def test_get_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow), - '__call__') as call: - client.get_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() - - -@pytest.mark.asyncio -async def test_get_flow_async(transport: str = 'grpc_asyncio', request_type=flow.GetFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.get_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_get_flow_async_from_dict(): - await test_get_flow_async(request_type=dict) - - -def test_get_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.GetFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - call.return_value = flow.Flow() - client.get_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.GetFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow()) - await client.get_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.Flow() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_flow( - name='name_value', - ) - - # Establish that the 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_flow_flattened_error(): - client = FlowsClient( - credentials=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_flow( - flow.GetFlowRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_flow_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.Flow() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_flow( - 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_flow_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow( - flow.GetFlowRequest(), - name='name_value', - ) - - -def test_update_flow(transport: str = 'grpc', request_type=gcdc_flow.UpdateFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.update_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_update_flow_from_dict(): - test_update_flow(request_type=dict) - - -def test_update_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow), - '__call__') as call: - client.update_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() - - -@pytest.mark.asyncio -async def test_update_flow_async(transport: str = 'grpc_asyncio', request_type=gcdc_flow.UpdateFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow( - name='name_value', - display_name='display_name_value', - description='description_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.update_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_update_flow_async_from_dict(): - await test_update_flow_async(request_type=dict) - - -def test_update_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_flow.UpdateFlowRequest() - - request.flow.name = 'flow.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - call.return_value = gcdc_flow.Flow() - client.update_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'flow.name=flow.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_flow.UpdateFlowRequest() - - request.flow.name = 'flow.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - await client.update_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'flow.name=flow.name/value', - ) in kw['metadata'] - - -def test_update_flow_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_flow( - flow=gcdc_flow.Flow(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].flow == gcdc_flow.Flow(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_flow_flattened_error(): - client = FlowsClient( - credentials=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_flow( - gcdc_flow.UpdateFlowRequest(), - flow=gcdc_flow.Flow(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_flow_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_flow.Flow() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_flow( - flow=gcdc_flow.Flow(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].flow == gcdc_flow.Flow(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_flow_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow( - gcdc_flow.UpdateFlowRequest(), - flow=gcdc_flow.Flow(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_train_flow(transport: str = 'grpc', request_type=flow.TrainFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.train_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_train_flow_from_dict(): - test_train_flow(request_type=dict) - - -def test_train_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow), - '__call__') as call: - client.train_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() - - -@pytest.mark.asyncio -async def test_train_flow_async(transport: str = 'grpc_asyncio', request_type=flow.TrainFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.train_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_train_flow_async_from_dict(): - await test_train_flow_async(request_type=dict) - - -def test_train_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.TrainFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.train_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_train_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.TrainFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.train_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_train_flow_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.train_flow( - name='name_value', - ) - - # Establish that the 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_train_flow_flattened_error(): - client = FlowsClient( - credentials=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_flow( - flow.TrainFlowRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_train_flow_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.train_flow), - '__call__') as call: - # 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_flow( - 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_train_flow_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow( - flow.TrainFlowRequest(), - name='name_value', - ) - - -def test_validate_flow(transport: str = 'grpc', request_type=flow.ValidateFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.FlowValidationResult( - name='name_value', - ) - response = client.validate_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == 'name_value' - - -def test_validate_flow_from_dict(): - test_validate_flow(request_type=dict) - - -def test_validate_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_flow), - '__call__') as call: - client.validate_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() - - -@pytest.mark.asyncio -async def test_validate_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ValidateFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult( - name='name_value', - )) - response = await client.validate_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_validate_flow_async_from_dict(): - await test_validate_flow_async(request_type=dict) - - -def test_validate_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ValidateFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_flow), - '__call__') as call: - call.return_value = flow.FlowValidationResult() - client.validate_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_validate_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ValidateFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.validate_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) - await client.validate_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_validation_result(transport: str = 'grpc', request_type=flow.GetFlowValidationResultRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.FlowValidationResult( - name='name_value', - ) - response = client.get_flow_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == 'name_value' - - -def test_get_flow_validation_result_from_dict(): - test_get_flow_validation_result(request_type=dict) - - -def test_get_flow_validation_result_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=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_flow_validation_result), - '__call__') as call: - client.get_flow_validation_result() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() - - -@pytest.mark.asyncio -async def test_get_flow_validation_result_async(transport: str = 'grpc_asyncio', request_type=flow.GetFlowValidationResultRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult( - name='name_value', - )) - response = await client.get_flow_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_flow_validation_result_async_from_dict(): - await test_get_flow_validation_result_async(request_type=dict) - - -def test_get_flow_validation_result_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.GetFlowValidationResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - call.return_value = flow.FlowValidationResult() - client.get_flow_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_validation_result_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.GetFlowValidationResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) - await client.get_flow_validation_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_flow_validation_result_flattened(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.FlowValidationResult() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_flow_validation_result( - name='name_value', - ) - - # Establish that the 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_flow_validation_result_flattened_error(): - client = FlowsClient( - credentials=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_flow_validation_result( - flow.GetFlowValidationResultRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_flow_validation_result_flattened_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_flow_validation_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = flow.FlowValidationResult() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.FlowValidationResult()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_flow_validation_result( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_flow_validation_result_flattened_error_async(): - client = FlowsAsyncClient( - credentials=ga_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_flow_validation_result( - flow.GetFlowValidationResultRequest(), - name='name_value', - ) - - -def test_import_flow(transport: str = 'grpc', request_type=flow.ImportFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ImportFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_flow_from_dict(): - test_import_flow(request_type=dict) - - -def test_import_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_flow), - '__call__') as call: - client.import_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ImportFlowRequest() - - -@pytest.mark.asyncio -async def test_import_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ImportFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.import_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ImportFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_flow_async_from_dict(): - await test_import_flow_async(request_type=dict) - - -def test_import_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ImportFlowRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_flow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ImportFlowRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_export_flow(transport: str = 'grpc', request_type=flow.ExportFlowRequest): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.export_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ExportFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_export_flow_from_dict(): - test_export_flow(request_type=dict) - - -def test_export_flow_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_flow), - '__call__') as call: - client.export_flow() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ExportFlowRequest() - - -@pytest.mark.asyncio -async def test_export_flow_async(transport: str = 'grpc_asyncio', request_type=flow.ExportFlowRequest): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_flow), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.export_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == flow.ExportFlowRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_flow_async_from_dict(): - await test_export_flow_async(request_type=dict) - - -def test_export_flow_field_headers(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ExportFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_flow), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_export_flow_field_headers_async(): - client = FlowsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = flow.ExportFlowRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_flow), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.export_flow(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.FlowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.FlowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FlowsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.FlowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = FlowsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.FlowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = FlowsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.FlowsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.FlowsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.FlowsGrpcTransport, - transports.FlowsGrpcAsyncIOTransport, -]) -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 = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.FlowsGrpcTransport, - ) - -def test_flows_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.FlowsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_flows_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.FlowsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_flow', - 'delete_flow', - 'list_flows', - 'get_flow', - 'update_flow', - 'train_flow', - 'validate_flow', - 'get_flow_validation_result', - 'import_flow', - 'export_flow', - ) - 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_flows_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FlowsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_flows_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FlowsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_flows_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.FlowsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_flows_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - FlowsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_flows_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - FlowsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FlowsGrpcTransport, - transports.FlowsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_flows_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.FlowsGrpcTransport, - transports.FlowsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_flows_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.FlowsGrpcTransport, grpc_helpers), - (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_flows_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.FlowsGrpcTransport, grpc_helpers), - (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_flows_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.FlowsGrpcTransport, grpc_helpers), - (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_flows_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) -def test_flows_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = 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_flows_host_no_port(): - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_flows_host_with_port(): - client = FlowsClient( - 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_flows_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FlowsGrpcTransport( - 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_flows_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.FlowsGrpcAsyncIOTransport( - 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.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) -def test_flows_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.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport]) -def test_flows_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_flows_grpc_lro_client(): - client = FlowsClient( - 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_flows_grpc_lro_async_client(): - client = FlowsAsyncClient( - 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_flow_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = FlowsClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "flow": "mussel", - } - path = FlowsClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_flow_path(path) - assert expected == actual - -def test_flow_validation_result_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format(project=project, location=location, agent=agent, flow=flow, ) - actual = FlowsClient.flow_validation_result_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_validation_result_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "flow": "octopus", - } - path = FlowsClient.flow_validation_result_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_flow_validation_result_path(path) - assert expected == actual - -def test_intent_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = FlowsClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "intent": "abalone", - } - path = FlowsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_intent_path(path) - assert expected == actual - -def test_page_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - actual = FlowsClient.page_path(project, location, agent, flow, page) - assert expected == actual - - -def test_parse_page_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "flow": "winkle", - "page": "nautilus", - } - path = FlowsClient.page_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_page_path(path) - assert expected == actual - -def test_transition_route_group_path(): - project = "scallop" - location = "abalone" - agent = "squid" - flow = "clam" - transition_route_group = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - actual = FlowsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) - assert expected == actual - - -def test_parse_transition_route_group_path(): - expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - "flow": "cuttlefish", - "transition_route_group": "mussel", - } - path = FlowsClient.transition_route_group_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_transition_route_group_path(path) - assert expected == actual - -def test_webhook_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - webhook = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = FlowsClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "webhook": "octopus", - } - path = FlowsClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = FlowsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = FlowsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = FlowsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = FlowsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = FlowsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = FlowsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = FlowsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = FlowsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.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 = FlowsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = FlowsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = FlowsClient.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.FlowsTransport, '_prep_wrapped_messages') as prep: - client = FlowsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.FlowsTransport, '_prep_wrapped_messages') as prep: - transport_class = FlowsClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py deleted file mode 100644 index 7f89a9e5..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py +++ /dev/null @@ -1,2429 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.intents import IntentsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.intents import IntentsClient -from google.cloud.dialogflowcx_v3beta1.services.intents import pagers -from google.cloud.dialogflowcx_v3beta1.services.intents import transports -from google.cloud.dialogflowcx_v3beta1.services.intents.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.intents.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import intent -from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3beta1.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', - ) - - # Establish that the 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_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', - ) - - -@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', - ) - - # Establish that 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_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', - ) - - -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', - priority=898, - is_fallback=True, - description='description_value', - ) - response = client.get_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -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', - priority=898, - is_fallback=True, - description='description_value', - )) - response = await client.get_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -@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', - ) - - # Establish that the 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_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', - ) - - -@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', - ) - - # Establish that 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_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', - ) - - -def test_create_intent(transport: str = 'grpc', request_type=gcdc_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 = gcdc_intent.Intent( - name='name_value', - display_name='display_name_value', - priority=898, - is_fallback=True, - description='description_value', - ) - response = client.create_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.CreateIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -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] == gcdc_intent.CreateIntentRequest() - - -@pytest.mark.asyncio -async def test_create_intent_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_intent.Intent( - name='name_value', - display_name='display_name_value', - priority=898, - is_fallback=True, - description='description_value', - )) - response = await client.create_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.CreateIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -@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 = gcdc_intent.CreateIntentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_intent), - '__call__') as call: - call.return_value = gcdc_intent.Intent() - client.create_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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 = gcdc_intent.CreateIntentRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) - await client.create_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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 = gcdc_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=gcdc_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 == gcdc_intent.Intent(name='name_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( - gcdc_intent.CreateIntentRequest(), - parent='parent_value', - intent=gcdc_intent.Intent(name='name_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 = gcdc_intent.Intent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_intent.Intent(name='name_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( - gcdc_intent.CreateIntentRequest(), - parent='parent_value', - intent=gcdc_intent.Intent(name='name_value'), - ) - - -def test_update_intent(transport: str = 'grpc', request_type=gcdc_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 = gcdc_intent.Intent( - name='name_value', - display_name='display_name_value', - priority=898, - is_fallback=True, - description='description_value', - ) - response = client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.UpdateIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -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] == gcdc_intent.UpdateIntentRequest() - - -@pytest.mark.asyncio -async def test_update_intent_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_intent.Intent( - name='name_value', - display_name='display_name_value', - priority=898, - is_fallback=True, - description='description_value', - )) - response = await client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.UpdateIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == 'description_value' - - -@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 = gcdc_intent.UpdateIntentRequest() - - request.intent.name = 'intent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_intent), - '__call__') as call: - call.return_value = gcdc_intent.Intent() - client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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 = gcdc_intent.UpdateIntentRequest() - - request.intent.name = 'intent.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) - await client.update_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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 = gcdc_intent.Intent() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_intent( - intent=gcdc_intent.Intent(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].intent == gcdc_intent.Intent(name='name_value') - assert args[0].update_mask == field_mask_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( - gcdc_intent.UpdateIntentRequest(), - intent=gcdc_intent.Intent(name='name_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 = gcdc_intent.Intent() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_intent.Intent(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].intent == gcdc_intent.Intent(name='name_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( - gcdc_intent.UpdateIntentRequest(), - intent=gcdc_intent.Intent(name='name_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_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.dialogflowcx_v3beta1.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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_intents_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_intents_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.IntentsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - 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.dialogflowcx_v3beta1.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_entity_type_path(): - project = "squid" - location = "clam" - agent = "whelk" - entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - actual = IntentsClient.entity_type_path(project, location, agent, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "entity_type": "mussel", - } - path = IntentsClient.entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = IntentsClient.parse_entity_type_path(path) - assert expected == actual - -def test_intent_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - intent = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = IntentsClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "intent": "octopus", - } - 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 = "oyster" - 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": "nudibranch", - } - 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 = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = IntentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - 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 = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = IntentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - 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 = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = IntentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - 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 = "squid" - location = "clam" - 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": "whelk", - "location": "octopus", - } - 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py deleted file mode 100644 index 4d8ad741..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py +++ /dev/null @@ -1,2504 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.pages import PagesAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.pages import PagesClient -from google.cloud.dialogflowcx_v3beta1.services.pages import pagers -from google.cloud.dialogflowcx_v3beta1.services.pages import transports -from google.cloud.dialogflowcx_v3beta1.services.pages.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.pages.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import fulfillment -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page -from google.cloud.dialogflowcx_v3beta1.types import response_message -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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 PagesClient._get_default_mtls_endpoint(None) is None - assert PagesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PagesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PagesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PagesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PagesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - PagesClient, - PagesAsyncClient, -]) -def test_pages_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", [ - PagesClient, - PagesAsyncClient, -]) -def test_pages_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_pages_client_get_transport_class(): - transport = PagesClient.get_transport_class() - available_transports = [ - transports.PagesGrpcTransport, - ] - assert transport in available_transports - - transport = PagesClient.get_transport_class("grpc") - assert transport == transports.PagesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PagesClient, transports.PagesGrpcTransport, "grpc"), - (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(PagesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesClient)) -@mock.patch.object(PagesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesAsyncClient)) -def test_pages_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(PagesClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=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(PagesClient, '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", [ - (PagesClient, transports.PagesGrpcTransport, "grpc", "true"), - (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PagesClient, transports.PagesGrpcTransport, "grpc", "false"), - (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(PagesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesClient)) -@mock.patch.object(PagesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PagesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_pages_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", [ - (PagesClient, transports.PagesGrpcTransport, "grpc"), - (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_pages_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", [ - (PagesClient, transports.PagesGrpcTransport, "grpc"), - (PagesAsyncClient, transports.PagesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_pages_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_pages_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PagesClient( - 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_pages(transport: str = 'grpc', request_type=page.ListPagesRequest): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_pages), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.ListPagesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_pages(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPagesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_pages_from_dict(): - test_list_pages(request_type=dict) - - -def test_list_pages_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PagesClient( - credentials=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_pages), - '__call__') as call: - client.list_pages() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() - - -@pytest.mark.asyncio -async def test_list_pages_async(transport: str = 'grpc_asyncio', request_type=page.ListPagesRequest): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_pages), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_pages(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPagesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_pages_async_from_dict(): - await test_list_pages_async(request_type=dict) - - -def test_list_pages_field_headers(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.ListPagesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - call.return_value = page.ListPagesResponse() - client.list_pages(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_pages_field_headers_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.ListPagesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse()) - await client.list_pages(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_pages_flattened(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.ListPagesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_pages( - parent='parent_value', - ) - - # Establish that the 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_pages_flattened_error(): - client = PagesClient( - credentials=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_pages( - page.ListPagesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_pages_flattened_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.ListPagesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.ListPagesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_pages( - 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_pages_flattened_error_async(): - client = PagesAsyncClient( - credentials=ga_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_pages( - page.ListPagesRequest(), - parent='parent_value', - ) - - -def test_list_pages_pager(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - page.Page(), - ], - next_page_token='abc', - ), - page.ListPagesResponse( - pages=[], - next_page_token='def', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - ], - next_page_token='ghi', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_pages(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, page.Page) - for i in results) - -def test_list_pages_pages(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - page.Page(), - ], - next_page_token='abc', - ), - page.ListPagesResponse( - pages=[], - next_page_token='def', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - ], - next_page_token='ghi', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - ], - ), - RuntimeError, - ) - pages = list(client.list_pages(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_pages_async_pager(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - page.Page(), - ], - next_page_token='abc', - ), - page.ListPagesResponse( - pages=[], - next_page_token='def', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - ], - next_page_token='ghi', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_pages(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, page.Page) - for i in responses) - -@pytest.mark.asyncio -async def test_list_pages_async_pages(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_pages), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - page.Page(), - ], - next_page_token='abc', - ), - page.ListPagesResponse( - pages=[], - next_page_token='def', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - ], - next_page_token='ghi', - ), - page.ListPagesResponse( - pages=[ - page.Page(), - page.Page(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_pages(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_page(transport: str = 'grpc', request_type=page.GetPageRequest): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.get_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_get_page_from_dict(): - test_get_page(request_type=dict) - - -def test_get_page_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PagesClient( - credentials=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_page), - '__call__') as call: - client.get_page() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() - - -@pytest.mark.asyncio -async def test_get_page_async(transport: str = 'grpc_asyncio', request_type=page.GetPageRequest): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.get_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_get_page_async_from_dict(): - await test_get_page_async(request_type=dict) - - -def test_get_page_field_headers(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.GetPageRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_page), - '__call__') as call: - call.return_value = page.Page() - client.get_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_page_field_headers_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.GetPageRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_page), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.Page()) - await client.get_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_page_flattened(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.Page() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_page( - name='name_value', - ) - - # Establish that the 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_page_flattened_error(): - client = PagesClient( - credentials=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_page( - page.GetPageRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_page_flattened_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = page.Page() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.Page()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_page( - 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_page_flattened_error_async(): - client = PagesAsyncClient( - credentials=ga_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_page( - page.GetPageRequest(), - name='name_value', - ) - - -def test_create_page(transport: str = 'grpc', request_type=gcdc_page.CreatePageRequest): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.create_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_create_page_from_dict(): - test_create_page(request_type=dict) - - -def test_create_page_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PagesClient( - credentials=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_page), - '__call__') as call: - client.create_page() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() - - -@pytest.mark.asyncio -async def test_create_page_async(transport: str = 'grpc_asyncio', request_type=gcdc_page.CreatePageRequest): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.create_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_create_page_async_from_dict(): - await test_create_page_async(request_type=dict) - - -def test_create_page_field_headers(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_page.CreatePageRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_page), - '__call__') as call: - call.return_value = gcdc_page.Page() - client.create_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_page_field_headers_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_page.CreatePageRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_page), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - await client.create_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_page_flattened(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_page( - parent='parent_value', - page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') - - -def test_create_page_flattened_error(): - client = PagesClient( - credentials=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_page( - gcdc_page.CreatePageRequest(), - parent='parent_value', - page=gcdc_page.Page(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_page_flattened_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_page( - parent='parent_value', - page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') - - -@pytest.mark.asyncio -async def test_create_page_flattened_error_async(): - client = PagesAsyncClient( - credentials=ga_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_page( - gcdc_page.CreatePageRequest(), - parent='parent_value', - page=gcdc_page.Page(name='name_value'), - ) - - -def test_update_page(transport: str = 'grpc', request_type=gcdc_page.UpdatePageRequest): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - ) - response = client.update_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -def test_update_page_from_dict(): - test_update_page(request_type=dict) - - -def test_update_page_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PagesClient( - credentials=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_page), - '__call__') as call: - client.update_page() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() - - -@pytest.mark.asyncio -async def test_update_page_async(transport: str = 'grpc_asyncio', request_type=gcdc_page.UpdatePageRequest): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page( - name='name_value', - display_name='display_name_value', - transition_route_groups=['transition_route_groups_value'], - )) - response = await client.update_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.transition_route_groups == ['transition_route_groups_value'] - - -@pytest.mark.asyncio -async def test_update_page_async_from_dict(): - await test_update_page_async(request_type=dict) - - -def test_update_page_field_headers(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_page.UpdatePageRequest() - - request.page.name = 'page.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_page), - '__call__') as call: - call.return_value = gcdc_page.Page() - client.update_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'page.name=page.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_page_field_headers_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_page.UpdatePageRequest() - - request.page.name = 'page.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_page), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - await client.update_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'page.name=page.name/value', - ) in kw['metadata'] - - -def test_update_page_flattened(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_page( - page=gcdc_page.Page(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].page == gcdc_page.Page(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_page_flattened_error(): - client = PagesClient( - credentials=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_page( - gcdc_page.UpdatePageRequest(), - page=gcdc_page.Page(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_page_flattened_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_page.Page() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_page( - page=gcdc_page.Page(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].page == gcdc_page.Page(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_page_flattened_error_async(): - client = PagesAsyncClient( - credentials=ga_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_page( - gcdc_page.UpdatePageRequest(), - page=gcdc_page.Page(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_page(transport: str = 'grpc', request_type=page.DeletePageRequest): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_page_from_dict(): - test_delete_page(request_type=dict) - - -def test_delete_page_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = PagesClient( - credentials=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_page), - '__call__') as call: - client.delete_page() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() - - -@pytest.mark.asyncio -async def test_delete_page_async(transport: str = 'grpc_asyncio', request_type=page.DeletePageRequest): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_page_async_from_dict(): - await test_delete_page_async(request_type=dict) - - -def test_delete_page_field_headers(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.DeletePageRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_page), - '__call__') as call: - call.return_value = None - client.delete_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_page_field_headers_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = page.DeletePageRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_page), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_page(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_page_flattened(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_page), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_page( - name='name_value', - ) - - # Establish that the 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_page_flattened_error(): - client = PagesClient( - credentials=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_page( - page.DeletePageRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_page_flattened_async(): - client = PagesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_page), - '__call__') as call: - # 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_page( - 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_page_flattened_error_async(): - client = PagesAsyncClient( - credentials=ga_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_page( - page.DeletePageRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PagesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PagesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PagesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PagesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PagesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PagesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PagesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PagesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PagesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PagesGrpcTransport, - transports.PagesGrpcAsyncIOTransport, -]) -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 = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PagesGrpcTransport, - ) - -def test_pages_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PagesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_pages_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PagesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_pages', - 'get_page', - 'create_page', - 'update_page', - 'delete_page', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_pages_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PagesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_pages_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PagesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_pages_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PagesTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_pages_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - PagesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_pages_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - PagesClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PagesGrpcTransport, - transports.PagesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_pages_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.PagesGrpcTransport, - transports.PagesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_pages_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PagesGrpcTransport, grpc_helpers), - (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_pages_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PagesGrpcTransport, grpc_helpers), - (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_pages_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.PagesGrpcTransport, grpc_helpers), - (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_pages_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) -def test_pages_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = 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_pages_host_no_port(): - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_pages_host_with_port(): - client = PagesClient( - 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_pages_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PagesGrpcTransport( - 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_pages_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PagesGrpcAsyncIOTransport( - 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.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) -def test_pages_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.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport]) -def test_pages_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_type_path(): - project = "squid" - location = "clam" - agent = "whelk" - entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - actual = PagesClient.entity_type_path(project, location, agent, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "entity_type": "mussel", - } - path = PagesClient.entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_entity_type_path(path) - assert expected == actual - -def test_flow_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = PagesClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "flow": "octopus", - } - path = PagesClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_flow_path(path) - assert expected == actual - -def test_intent_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = PagesClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "intent": "abalone", - } - path = PagesClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_intent_path(path) - assert expected == actual - -def test_page_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - actual = PagesClient.page_path(project, location, agent, flow, page) - assert expected == actual - - -def test_parse_page_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "flow": "winkle", - "page": "nautilus", - } - path = PagesClient.page_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_page_path(path) - assert expected == actual - -def test_transition_route_group_path(): - project = "scallop" - location = "abalone" - agent = "squid" - flow = "clam" - transition_route_group = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - actual = PagesClient.transition_route_group_path(project, location, agent, flow, transition_route_group) - assert expected == actual - - -def test_parse_transition_route_group_path(): - expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - "flow": "cuttlefish", - "transition_route_group": "mussel", - } - path = PagesClient.transition_route_group_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_transition_route_group_path(path) - assert expected == actual - -def test_webhook_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - webhook = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = PagesClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "webhook": "octopus", - } - path = PagesClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PagesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = PagesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = PagesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = PagesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PagesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = PagesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = PagesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = PagesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.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 = PagesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = PagesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PagesClient.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.PagesTransport, '_prep_wrapped_messages') as prep: - client = PagesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PagesTransport, '_prep_wrapped_messages') as prep: - transport_class = PagesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py deleted file mode 100644 index edd873cf..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py +++ /dev/null @@ -1,2419 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.security_settings_service import SecuritySettingsServiceAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import SecuritySettingsServiceClient -from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import pagers -from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import transports -from google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import security_settings -from google.cloud.dialogflowcx_v3beta1.types import security_settings as gcdc_security_settings -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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 SecuritySettingsServiceClient._get_default_mtls_endpoint(None) is None - assert SecuritySettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecuritySettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecuritySettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecuritySettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecuritySettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - SecuritySettingsServiceClient, - SecuritySettingsServiceAsyncClient, -]) -def test_security_settings_service_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", [ - SecuritySettingsServiceClient, - SecuritySettingsServiceAsyncClient, -]) -def test_security_settings_service_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_security_settings_service_client_get_transport_class(): - transport = SecuritySettingsServiceClient.get_transport_class() - available_transports = [ - transports.SecuritySettingsServiceGrpcTransport, - ] - assert transport in available_transports - - transport = SecuritySettingsServiceClient.get_transport_class("grpc") - assert transport == transports.SecuritySettingsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), - (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SecuritySettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceClient)) -@mock.patch.object(SecuritySettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceAsyncClient)) -def test_security_settings_service_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(SecuritySettingsServiceClient, '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(SecuritySettingsServiceClient, '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", [ - (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc", "true"), - (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc", "false"), - (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SecuritySettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceClient)) -@mock.patch.object(SecuritySettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecuritySettingsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_settings_service_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", [ - (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), - (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_settings_service_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", [ - (SecuritySettingsServiceClient, transports.SecuritySettingsServiceGrpcTransport, "grpc"), - (SecuritySettingsServiceAsyncClient, transports.SecuritySettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_settings_service_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_security_settings_service_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecuritySettingsServiceClient( - 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_security_settings(transport: str = 'grpc', request_type=gcdc_security_settings.CreateSecuritySettingsRequest): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - retention_window_days=2271, - ) - response = client.create_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -def test_create_security_settings_from_dict(): - test_create_security_settings(request_type=dict) - - -def test_create_security_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecuritySettingsServiceClient( - credentials=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_security_settings), - '__call__') as call: - client.create_security_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() - - -@pytest.mark.asyncio -async def test_create_security_settings_async(transport: str = 'grpc_asyncio', request_type=gcdc_security_settings.CreateSecuritySettingsRequest): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - )) - response = await client.create_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -@pytest.mark.asyncio -async def test_create_security_settings_async_from_dict(): - await test_create_security_settings_async(request_type=dict) - - -def test_create_security_settings_field_headers(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_security_settings.CreateSecuritySettingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_settings), - '__call__') as call: - call.return_value = gcdc_security_settings.SecuritySettings() - client.create_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_settings_field_headers_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_security_settings.CreateSecuritySettingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) - await client.create_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_settings_flattened(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_security_settings( - parent='parent_value', - security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') - - -def test_create_security_settings_flattened_error(): - client = SecuritySettingsServiceClient( - credentials=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_security_settings( - gcdc_security_settings.CreateSecuritySettingsRequest(), - parent='parent_value', - security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_security_settings_flattened_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_security_settings( - parent='parent_value', - security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') - - -@pytest.mark.asyncio -async def test_create_security_settings_flattened_error_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_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_security_settings( - gcdc_security_settings.CreateSecuritySettingsRequest(), - parent='parent_value', - security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), - ) - - -def test_get_security_settings(transport: str = 'grpc', request_type=security_settings.GetSecuritySettingsRequest): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - retention_window_days=2271, - ) - response = client.get_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -def test_get_security_settings_from_dict(): - test_get_security_settings(request_type=dict) - - -def test_get_security_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecuritySettingsServiceClient( - credentials=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_security_settings), - '__call__') as call: - client.get_security_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() - - -@pytest.mark.asyncio -async def test_get_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.GetSecuritySettingsRequest): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - )) - response = await client.get_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -@pytest.mark.asyncio -async def test_get_security_settings_async_from_dict(): - await test_get_security_settings_async(request_type=dict) - - -def test_get_security_settings_field_headers(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.GetSecuritySettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_settings), - '__call__') as call: - call.return_value = security_settings.SecuritySettings() - client.get_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_security_settings_field_headers_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.GetSecuritySettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings()) - await client.get_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_security_settings_flattened(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_security_settings( - name='name_value', - ) - - # Establish that the 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_security_settings_flattened_error(): - client = SecuritySettingsServiceClient( - credentials=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_security_settings( - security_settings.GetSecuritySettingsRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_security_settings_flattened_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.SecuritySettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.SecuritySettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_security_settings( - 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_security_settings_flattened_error_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_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_security_settings( - security_settings.GetSecuritySettingsRequest(), - name='name_value', - ) - - -def test_update_security_settings(transport: str = 'grpc', request_type=gcdc_security_settings.UpdateSecuritySettingsRequest): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - retention_window_days=2271, - ) - response = client.update_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -def test_update_security_settings_from_dict(): - test_update_security_settings(request_type=dict) - - -def test_update_security_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecuritySettingsServiceClient( - credentials=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_security_settings), - '__call__') as call: - client.update_security_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() - - -@pytest.mark.asyncio -async def test_update_security_settings_async(transport: str = 'grpc_asyncio', request_type=gcdc_security_settings.UpdateSecuritySettingsRequest): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings( - name='name_value', - display_name='display_name_value', - redaction_strategy=gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE, - redaction_scope=gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE, - inspect_template='inspect_template_value', - purge_data_types=[gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY], - )) - response = await client.update_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE - assert response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE - assert response.inspect_template == 'inspect_template_value' - assert response.purge_data_types == [gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY] - - -@pytest.mark.asyncio -async def test_update_security_settings_async_from_dict(): - await test_update_security_settings_async(request_type=dict) - - -def test_update_security_settings_field_headers(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_security_settings.UpdateSecuritySettingsRequest() - - request.security_settings.name = 'security_settings.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_settings), - '__call__') as call: - call.return_value = gcdc_security_settings.SecuritySettings() - client.update_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_settings.name=security_settings.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_settings_field_headers_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_security_settings.UpdateSecuritySettingsRequest() - - request.security_settings.name = 'security_settings.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) - await client.update_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'security_settings.name=security_settings.name/value', - ) in kw['metadata'] - - -def test_update_security_settings_flattened(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_settings( - security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_security_settings_flattened_error(): - client = SecuritySettingsServiceClient( - credentials=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_security_settings( - gcdc_security_settings.UpdateSecuritySettingsRequest(), - security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_security_settings_flattened_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_security_settings.SecuritySettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_security_settings.SecuritySettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_settings( - security_settings=gcdc_security_settings.SecuritySettings(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].security_settings == gcdc_security_settings.SecuritySettings(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_security_settings_flattened_error_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_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_security_settings( - gcdc_security_settings.UpdateSecuritySettingsRequest(), - security_settings=gcdc_security_settings.SecuritySettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_list_security_settings(transport: str = 'grpc', request_type=security_settings.ListSecuritySettingsRequest): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.ListSecuritySettingsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecuritySettingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_security_settings_from_dict(): - test_list_security_settings(request_type=dict) - - -def test_list_security_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecuritySettingsServiceClient( - credentials=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_security_settings), - '__call__') as call: - client.list_security_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() - - -@pytest.mark.asyncio -async def test_list_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.ListSecuritySettingsRequest): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecuritySettingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_security_settings_async_from_dict(): - await test_list_security_settings_async(request_type=dict) - - -def test_list_security_settings_field_headers(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.ListSecuritySettingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - call.return_value = security_settings.ListSecuritySettingsResponse() - client.list_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_security_settings_field_headers_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.ListSecuritySettingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse()) - await client.list_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_security_settings_flattened(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.ListSecuritySettingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_security_settings( - parent='parent_value', - ) - - # Establish that the 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_security_settings_flattened_error(): - client = SecuritySettingsServiceClient( - credentials=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_security_settings( - security_settings.ListSecuritySettingsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_security_settings_flattened_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = security_settings.ListSecuritySettingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(security_settings.ListSecuritySettingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_security_settings( - 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_security_settings_flattened_error_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_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_security_settings( - security_settings.ListSecuritySettingsRequest(), - parent='parent_value', - ) - - -def test_list_security_settings_pager(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - next_page_token='abc', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[], - next_page_token='def', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - ], - next_page_token='ghi', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_security_settings(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, security_settings.SecuritySettings) - for i in results) - -def test_list_security_settings_pages(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - next_page_token='abc', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[], - next_page_token='def', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - ], - next_page_token='ghi', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - ), - RuntimeError, - ) - pages = list(client.list_security_settings(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_security_settings_async_pager(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - next_page_token='abc', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[], - next_page_token='def', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - ], - next_page_token='ghi', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_security_settings(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, security_settings.SecuritySettings) - for i in responses) - -@pytest.mark.asyncio -async def test_list_security_settings_async_pages(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_security_settings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - next_page_token='abc', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[], - next_page_token='def', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - ], - next_page_token='ghi', - ), - security_settings.ListSecuritySettingsResponse( - security_settings=[ - security_settings.SecuritySettings(), - security_settings.SecuritySettings(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_security_settings(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_delete_security_settings(transport: str = 'grpc', request_type=security_settings.DeleteSecuritySettingsRequest): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_security_settings_from_dict(): - test_delete_security_settings(request_type=dict) - - -def test_delete_security_settings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SecuritySettingsServiceClient( - credentials=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_security_settings), - '__call__') as call: - client.delete_security_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() - - -@pytest.mark.asyncio -async def test_delete_security_settings_async(transport: str = 'grpc_asyncio', request_type=security_settings.DeleteSecuritySettingsRequest): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_security_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_security_settings_async_from_dict(): - await test_delete_security_settings_async(request_type=dict) - - -def test_delete_security_settings_field_headers(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.DeleteSecuritySettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_settings), - '__call__') as call: - call.return_value = None - client.delete_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_security_settings_field_headers_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = security_settings.DeleteSecuritySettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_security_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_security_settings_flattened(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_settings), - '__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_security_settings( - 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_security_settings_flattened_error(): - client = SecuritySettingsServiceClient( - credentials=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_security_settings( - security_settings.DeleteSecuritySettingsRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_security_settings_flattened_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_security_settings), - '__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_security_settings( - 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_security_settings_flattened_error_async(): - client = SecuritySettingsServiceAsyncClient( - credentials=ga_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_security_settings( - security_settings.DeleteSecuritySettingsRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecuritySettingsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecuritySettingsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecuritySettingsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecuritySettingsServiceGrpcTransport, - transports.SecuritySettingsServiceGrpcAsyncIOTransport, -]) -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 = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecuritySettingsServiceGrpcTransport, - ) - -def test_security_settings_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecuritySettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_settings_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecuritySettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_security_settings', - 'get_security_settings', - 'update_security_settings', - 'list_security_settings', - 'delete_security_settings', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_security_settings_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecuritySettingsServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecuritySettingsServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_security_settings_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecuritySettingsServiceTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_security_settings_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SecuritySettingsServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - SecuritySettingsServiceClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecuritySettingsServiceGrpcTransport, - transports.SecuritySettingsServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_security_settings_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecuritySettingsServiceGrpcTransport, - transports.SecuritySettingsServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_security_settings_service_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), - (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_security_settings_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), - (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_security_settings_service_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), - (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_security_settings_service_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) -def test_security_settings_service_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_security_settings_service_host_no_port(): - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_security_settings_service_host_with_port(): - client = SecuritySettingsServiceClient( - 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_security_settings_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecuritySettingsServiceGrpcTransport( - 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_security_settings_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( - 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.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) -def test_security_settings_service_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.SecuritySettingsServiceGrpcTransport, transports.SecuritySettingsServiceGrpcAsyncIOTransport]) -def test_security_settings_service_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_security_settings_path(): - project = "squid" - location = "clam" - security_settings = "whelk" - expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format(project=project, location=location, security_settings=security_settings, ) - actual = SecuritySettingsServiceClient.security_settings_path(project, location, security_settings) - assert expected == actual - - -def test_parse_security_settings_path(): - expected = { - "project": "octopus", - "location": "oyster", - "security_settings": "nudibranch", - } - path = SecuritySettingsServiceClient.security_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.parse_security_settings_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecuritySettingsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SecuritySettingsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecuritySettingsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SecuritySettingsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecuritySettingsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SecuritySettingsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SecuritySettingsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SecuritySettingsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.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 = SecuritySettingsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SecuritySettingsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecuritySettingsServiceClient.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.SecuritySettingsServiceTransport, '_prep_wrapped_messages') as prep: - client = SecuritySettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecuritySettingsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SecuritySettingsServiceClient.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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py deleted file mode 100644 index e149c587..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py +++ /dev/null @@ -1,2373 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.session_entity_types import SessionEntityTypesAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import SessionEntityTypesClient -from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import pagers -from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import transports -from google.cloud.dialogflowcx_v3beta1.services.session_entity_types.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.session_entity_types.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import entity_type -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type as gcdc_session_entity_type -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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.dialogflowcx_v3beta1.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=gcdc_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 = gcdc_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - ) - response = client.create_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == 'name_value' - assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE - - -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] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() - - -@pytest.mark.asyncio -async def test_create_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - )) - response = await client.create_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == 'name_value' - assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE - - -@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 = gcdc_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 = gcdc_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 = gcdc_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(gcdc_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 = gcdc_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_session_entity_type( - parent='parent_value', - session_entity_type=gcdc_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 == gcdc_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( - gcdc_session_entity_type.CreateSessionEntityTypeRequest(), - parent='parent_value', - session_entity_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( - gcdc_session_entity_type.CreateSessionEntityTypeRequest(), - parent='parent_value', - session_entity_type=gcdc_session_entity_type.SessionEntityType(name='name_value'), - ) - - -def test_update_session_entity_type(transport: str = 'grpc', request_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - ) - response = client.update_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == 'name_value' - assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE - - -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] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() - - -@pytest.mark.asyncio -async def test_update_session_entity_type_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_session_entity_type.SessionEntityType( - name='name_value', - entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, - )) - response = await client.update_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == 'name_value' - assert response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE - - -@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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() - - request.session_entity_type.name = 'session_entity_type.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_session_entity_type), - '__call__') as call: - call.return_value = gcdc_session_entity_type.SessionEntityType() - client.update_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() - - request.session_entity_type.name = 'session_entity_type.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_session_entity_type), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_session_entity_type.SessionEntityType()) - await client.update_session_entity_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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 = gcdc_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_session_entity_type( - session_entity_type=gcdc_session_entity_type.SessionEntityType(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].session_entity_type == gcdc_session_entity_type.SessionEntityType(name='name_value') - assert args[0].update_mask == field_mask_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( - gcdc_session_entity_type.UpdateSessionEntityTypeRequest(), - session_entity_type=gcdc_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 = gcdc_session_entity_type.SessionEntityType() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( - gcdc_session_entity_type.UpdateSessionEntityTypeRequest(), - session_entity_type=gcdc_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.dialogflowcx_v3beta1.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.dialogflowcx_v3beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_session_entity_types_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionEntityTypesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - 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.dialogflowcx_v3beta1.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" - location = "clam" - agent = "whelk" - session = "octopus" - entity_type = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, session=session, entity_type=entity_type, ) - actual = SessionEntityTypesClient.session_entity_type_path(project, location, agent, session, entity_type) - assert expected == actual - - -def test_parse_session_entity_type_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "session": "winkle", - "entity_type": "nautilus", - } - 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 = "scallop" - 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": "abalone", - } - 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 = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = SessionEntityTypesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - 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 = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SessionEntityTypesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - 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 = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = SessionEntityTypesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - 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": "winkle", - "location": "nautilus", - } - 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py deleted file mode 100644 index 42799a8d..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py +++ /dev/null @@ -1,1708 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.sessions import SessionsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.sessions import SessionsClient -from google.cloud.dialogflowcx_v3beta1.services.sessions import transports -from google.cloud.dialogflowcx_v3beta1.services.sessions.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.sessions.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import audio_config -from google.cloud.dialogflowcx_v3beta1.types import entity_type -from google.cloud.dialogflowcx_v3beta1.types import intent -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import session -from google.cloud.dialogflowcx_v3beta1.types import session_entity_type -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # 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.dialogflowcx_v3beta1.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=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 = session.DetectIntentResponse( - response_id='response_id_value', - output_audio=b'output_audio_blob', - ) - response = client.detect_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == session.DetectIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.DetectIntentResponse) - assert response.response_id == 'response_id_value' - assert response.output_audio == b'output_audio_blob' - - -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] == session.DetectIntentRequest() - - -@pytest.mark.asyncio -async def test_detect_intent_async(transport: str = 'grpc_asyncio', request_type=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(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] == session.DetectIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.DetectIntentResponse) - assert response.response_id == 'response_id_value' - assert response.output_audio == b'output_audio_blob' - - -@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 = session.DetectIntentRequest() - - request.session = 'session/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.detect_intent), - '__call__') as call: - call.return_value = session.DetectIntentResponse() - client.detect_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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 = 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(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_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_match_intent(transport: str = 'grpc', request_type=session.MatchIntentRequest): - 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.match_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = session.MatchIntentResponse( - text='text_value', - ) - response = client.match_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.MatchIntentResponse) - - -def test_match_intent_from_dict(): - test_match_intent(request_type=dict) - - -def test_match_intent_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.match_intent), - '__call__') as call: - client.match_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() - - -@pytest.mark.asyncio -async def test_match_intent_async(transport: str = 'grpc_asyncio', request_type=session.MatchIntentRequest): - 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.match_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session.MatchIntentResponse( - )) - response = await client.match_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.MatchIntentResponse) - - -@pytest.mark.asyncio -async def test_match_intent_async_from_dict(): - await test_match_intent_async(request_type=dict) - - -def test_match_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 = session.MatchIntentRequest() - - request.session = 'session/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.match_intent), - '__call__') as call: - call.return_value = session.MatchIntentResponse() - client.match_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_match_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 = session.MatchIntentRequest() - - request.session = 'session/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.match_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session.MatchIntentResponse()) - await client.match_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_fulfill_intent(transport: str = 'grpc', request_type=session.FulfillIntentRequest): - 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.fulfill_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = session.FulfillIntentResponse( - response_id='response_id_value', - output_audio=b'output_audio_blob', - ) - response = client.fulfill_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.FulfillIntentResponse) - assert response.response_id == 'response_id_value' - assert response.output_audio == b'output_audio_blob' - - -def test_fulfill_intent_from_dict(): - test_fulfill_intent(request_type=dict) - - -def test_fulfill_intent_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SessionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fulfill_intent), - '__call__') as call: - client.fulfill_intent() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() - - -@pytest.mark.asyncio -async def test_fulfill_intent_async(transport: str = 'grpc_asyncio', request_type=session.FulfillIntentRequest): - 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.fulfill_intent), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(session.FulfillIntentResponse( - response_id='response_id_value', - output_audio=b'output_audio_blob', - )) - response = await client.fulfill_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, session.FulfillIntentResponse) - assert response.response_id == 'response_id_value' - assert response.output_audio == b'output_audio_blob' - - -@pytest.mark.asyncio -async def test_fulfill_intent_async_from_dict(): - await test_fulfill_intent_async(request_type=dict) - - -def test_fulfill_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 = session.FulfillIntentRequest() - - request.match_intent_request.session = 'match_intent_request.session/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fulfill_intent), - '__call__') as call: - call.return_value = session.FulfillIntentResponse() - client.fulfill_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'match_intent_request.session=match_intent_request.session/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_fulfill_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 = session.FulfillIntentRequest() - - request.match_intent_request.session = 'match_intent_request.session/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fulfill_intent), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(session.FulfillIntentResponse()) - await client.fulfill_intent(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'match_intent_request.session=match_intent_request.session/value', - ) in kw['metadata'] - - -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.dialogflowcx_v3beta1.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', - 'match_intent', - 'fulfill_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.dialogflowcx_v3beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SessionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_sessions_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (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.dialogflowcx_v3beta1.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_entity_type_path(): - project = "squid" - location = "clam" - agent = "whelk" - entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - actual = SessionsClient.entity_type_path(project, location, agent, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "entity_type": "mussel", - } - path = SessionsClient.entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_entity_type_path(path) - assert expected == actual - -def test_flow_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = SessionsClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "flow": "octopus", - } - path = SessionsClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_flow_path(path) - assert expected == actual - -def test_intent_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = SessionsClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "intent": "abalone", - } - path = SessionsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_intent_path(path) - assert expected == actual - -def test_page_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - actual = SessionsClient.page_path(project, location, agent, flow, page) - assert expected == actual - - -def test_parse_page_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "flow": "winkle", - "page": "nautilus", - } - path = SessionsClient.page_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_page_path(path) - assert expected == actual - -def test_session_path(): - project = "scallop" - location = "abalone" - agent = "squid" - session = "clam" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format(project=project, location=location, agent=agent, session=session, ) - actual = SessionsClient.session_path(project, location, agent, session) - assert expected == actual - - -def test_parse_session_path(): - expected = { - "project": "whelk", - "location": "octopus", - "agent": "oyster", - "session": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - agent = "winkle" - session = "nautilus" - entity_type = "scallop" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, session=session, entity_type=entity_type, ) - actual = SessionsClient.session_entity_type_path(project, location, agent, session, entity_type) - assert expected == actual - - -def test_parse_session_entity_type_path(): - expected = { - "project": "abalone", - "location": "squid", - "agent": "clam", - "session": "whelk", - "entity_type": "octopus", - } - 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_transition_route_group_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - flow = "mussel" - transition_route_group = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - actual = SessionsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) - assert expected == actual - - -def test_parse_transition_route_group_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "agent": "abalone", - "flow": "squid", - "transition_route_group": "clam", - } - path = SessionsClient.transition_route_group_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_transition_route_group_path(path) - assert expected == actual - -def test_webhook_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - webhook = "nudibranch" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = SessionsClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "agent": "winkle", - "webhook": "nautilus", - } - path = SessionsClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = SessionsClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - 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": "abalone", - } - 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 = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = SessionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - 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 = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SessionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - 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 = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = SessionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - 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": "winkle", - "location": "nautilus", - } - 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py deleted file mode 100644 index a0fb6bc1..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py +++ /dev/null @@ -1,4061 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.test_cases import TestCasesAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.test_cases import TestCasesClient -from google.cloud.dialogflowcx_v3beta1.services.test_cases import pagers -from google.cloud.dialogflowcx_v3beta1.services.test_cases import transports -from google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import audio_config -from google.cloud.dialogflowcx_v3beta1.types import fulfillment -from google.cloud.dialogflowcx_v3beta1.types import intent -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import response_message -from google.cloud.dialogflowcx_v3beta1.types import session -from google.cloud.dialogflowcx_v3beta1.types import test_case -from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 -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 struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - -def client_cert_source_callback(): - 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 TestCasesClient._get_default_mtls_endpoint(None) is None - assert TestCasesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TestCasesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TestCasesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TestCasesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TestCasesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - TestCasesClient, - TestCasesAsyncClient, -]) -def test_test_cases_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", [ - TestCasesClient, - TestCasesAsyncClient, -]) -def test_test_cases_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_test_cases_client_get_transport_class(): - transport = TestCasesClient.get_transport_class() - available_transports = [ - transports.TestCasesGrpcTransport, - ] - assert transport in available_transports - - transport = TestCasesClient.get_transport_class("grpc") - assert transport == transports.TestCasesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), - (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(TestCasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesClient)) -@mock.patch.object(TestCasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesAsyncClient)) -def test_test_cases_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(TestCasesClient, '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(TestCasesClient, '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", [ - (TestCasesClient, transports.TestCasesGrpcTransport, "grpc", "true"), - (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TestCasesClient, transports.TestCasesGrpcTransport, "grpc", "false"), - (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(TestCasesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesClient)) -@mock.patch.object(TestCasesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TestCasesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_test_cases_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", [ - (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), - (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_test_cases_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", [ - (TestCasesClient, transports.TestCasesGrpcTransport, "grpc"), - (TestCasesAsyncClient, transports.TestCasesGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_test_cases_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_test_cases_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TestCasesClient( - 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_test_cases(transport: str = 'grpc', request_type=test_case.ListTestCasesRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCasesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCasesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_test_cases_from_dict(): - test_list_test_cases(request_type=dict) - - -def test_list_test_cases_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_cases), - '__call__') as call: - client.list_test_cases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() - - -@pytest.mark.asyncio -async def test_list_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ListTestCasesRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCasesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_test_cases_async_from_dict(): - await test_list_test_cases_async(request_type=dict) - - -def test_list_test_cases_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ListTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - call.return_value = test_case.ListTestCasesResponse() - client.list_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_cases_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ListTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse()) - await client.list_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_cases_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCasesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_test_cases( - parent='parent_value', - ) - - # Establish that the 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_test_cases_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_test_cases( - test_case.ListTestCasesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_test_cases_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCasesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCasesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_test_cases( - 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_test_cases_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_test_cases( - test_case.ListTestCasesRequest(), - parent='parent_value', - ) - - -def test_list_test_cases_pager(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - test_case.TestCase(), - ], - next_page_token='abc', - ), - test_case.ListTestCasesResponse( - test_cases=[], - next_page_token='def', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - ], - next_page_token='ghi', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_test_cases(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, test_case.TestCase) - for i in results) - -def test_list_test_cases_pages(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - test_case.TestCase(), - ], - next_page_token='abc', - ), - test_case.ListTestCasesResponse( - test_cases=[], - next_page_token='def', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - ], - next_page_token='ghi', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - ], - ), - RuntimeError, - ) - pages = list(client.list_test_cases(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_test_cases_async_pager(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - test_case.TestCase(), - ], - next_page_token='abc', - ), - test_case.ListTestCasesResponse( - test_cases=[], - next_page_token='def', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - ], - next_page_token='ghi', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_test_cases(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, test_case.TestCase) - for i in responses) - -@pytest.mark.asyncio -async def test_list_test_cases_async_pages(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_cases), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - test_case.TestCase(), - ], - next_page_token='abc', - ), - test_case.ListTestCasesResponse( - test_cases=[], - next_page_token='def', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - ], - next_page_token='ghi', - ), - test_case.ListTestCasesResponse( - test_cases=[ - test_case.TestCase(), - test_case.TestCase(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_test_cases(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_batch_delete_test_cases(transport: str = 'grpc', request_type=test_case.BatchDeleteTestCasesRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.batch_delete_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_batch_delete_test_cases_from_dict(): - test_batch_delete_test_cases(request_type=dict) - - -def test_batch_delete_test_cases_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_cases), - '__call__') as call: - client.batch_delete_test_cases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() - - -@pytest.mark.asyncio -async def test_batch_delete_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.BatchDeleteTestCasesRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.batch_delete_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_batch_delete_test_cases_async_from_dict(): - await test_batch_delete_test_cases_async(request_type=dict) - - -def test_batch_delete_test_cases_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.BatchDeleteTestCasesRequest() - - 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_test_cases), - '__call__') as call: - call.return_value = None - client.batch_delete_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_cases_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.BatchDeleteTestCasesRequest() - - 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_test_cases), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.batch_delete_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_cases_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_test_cases), - '__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.batch_delete_test_cases( - 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_delete_test_cases_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.batch_delete_test_cases( - test_case.BatchDeleteTestCasesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_batch_delete_test_cases_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_test_cases), - '__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.batch_delete_test_cases( - 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_delete_test_cases_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.batch_delete_test_cases( - test_case.BatchDeleteTestCasesRequest(), - parent='parent_value', - ) - - -def test_get_test_case(transport: str = 'grpc', request_type=test_case.GetTestCaseRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - ) - response = client.get_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -def test_get_test_case_from_dict(): - test_get_test_case(request_type=dict) - - -def test_get_test_case_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - client.get_test_case() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() - - -@pytest.mark.asyncio -async def test_get_test_case_async(transport: str = 'grpc_asyncio', request_type=test_case.GetTestCaseRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - )) - response = await client.get_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -@pytest.mark.asyncio -async def test_get_test_case_async_from_dict(): - await test_get_test_case_async(request_type=dict) - - -def test_get_test_case_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.GetTestCaseRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - call.return_value = test_case.TestCase() - client.get_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_test_case_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.GetTestCaseRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase()) - await client.get_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_test_case_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCase() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_test_case( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_test_case_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_test_case( - test_case.GetTestCaseRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_test_case_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_test_case( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_test_case_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_test_case( - test_case.GetTestCaseRequest(), - name='name_value', - ) - - -def test_create_test_case(transport: str = 'grpc', request_type=gcdc_test_case.CreateTestCaseRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - ) - response = client.create_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -def test_create_test_case_from_dict(): - test_create_test_case(request_type=dict) - - -def test_create_test_case_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_case), - '__call__') as call: - client.create_test_case() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() - - -@pytest.mark.asyncio -async def test_create_test_case_async(transport: str = 'grpc_asyncio', request_type=gcdc_test_case.CreateTestCaseRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - )) - response = await client.create_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -@pytest.mark.asyncio -async def test_create_test_case_async_from_dict(): - await test_create_test_case_async(request_type=dict) - - -def test_create_test_case_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_test_case.CreateTestCaseRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - call.return_value = gcdc_test_case.TestCase() - client.create_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_case_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_test_case.CreateTestCaseRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) - await client.create_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_case_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_test_case( - parent='parent_value', - test_case=gcdc_test_case.TestCase(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].test_case == gcdc_test_case.TestCase(name='name_value') - - -def test_create_test_case_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_test_case( - gcdc_test_case.CreateTestCaseRequest(), - parent='parent_value', - test_case=gcdc_test_case.TestCase(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_test_case_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_test_case( - parent='parent_value', - test_case=gcdc_test_case.TestCase(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].test_case == gcdc_test_case.TestCase(name='name_value') - - -@pytest.mark.asyncio -async def test_create_test_case_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_test_case( - gcdc_test_case.CreateTestCaseRequest(), - parent='parent_value', - test_case=gcdc_test_case.TestCase(name='name_value'), - ) - - -def test_update_test_case(transport: str = 'grpc', request_type=gcdc_test_case.UpdateTestCaseRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - ) - response = client.update_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -def test_update_test_case_from_dict(): - test_update_test_case(request_type=dict) - - -def test_update_test_case_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_case), - '__call__') as call: - client.update_test_case() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() - - -@pytest.mark.asyncio -async def test_update_test_case_async(transport: str = 'grpc_asyncio', request_type=gcdc_test_case.UpdateTestCaseRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase( - name='name_value', - tags=['tags_value'], - display_name='display_name_value', - notes='notes_value', - )) - response = await client.update_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == 'name_value' - assert response.tags == ['tags_value'] - assert response.display_name == 'display_name_value' - assert response.notes == 'notes_value' - - -@pytest.mark.asyncio -async def test_update_test_case_async_from_dict(): - await test_update_test_case_async(request_type=dict) - - -def test_update_test_case_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_test_case.UpdateTestCaseRequest() - - request.test_case.name = 'test_case.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - call.return_value = gcdc_test_case.TestCase() - client.update_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'test_case.name=test_case.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_test_case_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_test_case.UpdateTestCaseRequest() - - request.test_case.name = 'test_case.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) - await client.update_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'test_case.name=test_case.name/value', - ) in kw['metadata'] - - -def test_update_test_case_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_test_case( - test_case=gcdc_test_case.TestCase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].test_case == gcdc_test_case.TestCase(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_test_case_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_test_case( - gcdc_test_case.UpdateTestCaseRequest(), - test_case=gcdc_test_case.TestCase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_test_case_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_test_case.TestCase() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_test_case.TestCase()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_test_case( - test_case=gcdc_test_case.TestCase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].test_case == gcdc_test_case.TestCase(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_test_case_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_test_case( - gcdc_test_case.UpdateTestCaseRequest(), - test_case=gcdc_test_case.TestCase(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_run_test_case(transport: str = 'grpc', request_type=test_case.RunTestCaseRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_test_case), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_test_case_from_dict(): - test_run_test_case(request_type=dict) - - -def test_run_test_case_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_test_case), - '__call__') as call: - client.run_test_case() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() - - -@pytest.mark.asyncio -async def test_run_test_case_async(transport: str = 'grpc_asyncio', request_type=test_case.RunTestCaseRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_test_case), - '__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.run_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_run_test_case_async_from_dict(): - await test_run_test_case_async(request_type=dict) - - -def test_run_test_case_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.RunTestCaseRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_test_case), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_run_test_case_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.RunTestCaseRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_test_case), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_test_case(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_batch_run_test_cases(transport: str = 'grpc', request_type=test_case.BatchRunTestCasesRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.batch_run_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_batch_run_test_cases_from_dict(): - test_batch_run_test_cases(request_type=dict) - - -def test_batch_run_test_cases_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_run_test_cases), - '__call__') as call: - client.batch_run_test_cases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() - - -@pytest.mark.asyncio -async def test_batch_run_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.BatchRunTestCasesRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_test_cases), - '__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_run_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_batch_run_test_cases_async_from_dict(): - await test_batch_run_test_cases_async(request_type=dict) - - -def test_batch_run_test_cases_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.BatchRunTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_test_cases), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.batch_run_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_run_test_cases_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.BatchRunTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_run_test_cases), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.batch_run_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] - - -def test_calculate_coverage(transport: str = 'grpc', request_type=test_case.CalculateCoverageRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.calculate_coverage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.CalculateCoverageResponse( - agent='agent_value', - intent_coverage=test_case.IntentCoverage(intents=[test_case.IntentCoverage.Intent(intent='intent_value')]), - ) - response = client.calculate_coverage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.CalculateCoverageResponse) - assert response.agent == 'agent_value' - - -def test_calculate_coverage_from_dict(): - test_calculate_coverage(request_type=dict) - - -def test_calculate_coverage_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.calculate_coverage), - '__call__') as call: - client.calculate_coverage() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() - - -@pytest.mark.asyncio -async def test_calculate_coverage_async(transport: str = 'grpc_asyncio', request_type=test_case.CalculateCoverageRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.calculate_coverage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.CalculateCoverageResponse( - agent='agent_value', - )) - response = await client.calculate_coverage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.CalculateCoverageResponse) - assert response.agent == 'agent_value' - - -@pytest.mark.asyncio -async def test_calculate_coverage_async_from_dict(): - await test_calculate_coverage_async(request_type=dict) - - -def test_calculate_coverage_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.CalculateCoverageRequest() - - request.agent = 'agent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.calculate_coverage), - '__call__') as call: - call.return_value = test_case.CalculateCoverageResponse() - client.calculate_coverage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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=agent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_calculate_coverage_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.CalculateCoverageRequest() - - request.agent = 'agent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.calculate_coverage), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.CalculateCoverageResponse()) - await client.calculate_coverage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'agent=agent/value', - ) in kw['metadata'] - - -def test_import_test_cases(transport: str = 'grpc', request_type=test_case.ImportTestCasesRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_test_cases_from_dict(): - test_import_test_cases(request_type=dict) - - -def test_import_test_cases_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_cases), - '__call__') as call: - client.import_test_cases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() - - -@pytest.mark.asyncio -async def test_import_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ImportTestCasesRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_test_cases), - '__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_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_test_cases_async_from_dict(): - await test_import_test_cases_async(request_type=dict) - - -def test_import_test_cases_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ImportTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_test_cases), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_cases_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ImportTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_test_cases), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_cases(transport: str = 'grpc', request_type=test_case.ExportTestCasesRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_test_cases), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.export_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_export_test_cases_from_dict(): - test_export_test_cases(request_type=dict) - - -def test_export_test_cases_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_cases), - '__call__') as call: - client.export_test_cases() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() - - -@pytest.mark.asyncio -async def test_export_test_cases_async(transport: str = 'grpc_asyncio', request_type=test_case.ExportTestCasesRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_test_cases), - '__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_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_test_cases_async_from_dict(): - await test_export_test_cases_async(request_type=dict) - - -def test_export_test_cases_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ExportTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_test_cases), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_cases_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ExportTestCasesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_test_cases), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.export_test_cases(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_case_results(transport: str = 'grpc', request_type=test_case.ListTestCaseResultsRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCaseResultsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_test_case_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCaseResultsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_test_case_results_from_dict(): - test_list_test_case_results(request_type=dict) - - -def test_list_test_case_results_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=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_test_case_results), - '__call__') as call: - client.list_test_case_results() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() - - -@pytest.mark.asyncio -async def test_list_test_case_results_async(transport: str = 'grpc_asyncio', request_type=test_case.ListTestCaseResultsRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_test_case_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCaseResultsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_test_case_results_async_from_dict(): - await test_list_test_case_results_async(request_type=dict) - - -def test_list_test_case_results_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ListTestCaseResultsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - call.return_value = test_case.ListTestCaseResultsResponse() - client.list_test_case_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_test_case_results_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.ListTestCaseResultsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse()) - await client.list_test_case_results(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_test_case_results_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCaseResultsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_test_case_results( - parent='parent_value', - ) - - # Establish that the 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_test_case_results_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_test_case_results( - test_case.ListTestCaseResultsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_test_case_results_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.ListTestCaseResultsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.ListTestCaseResultsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_test_case_results( - 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_test_case_results_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_test_case_results( - test_case.ListTestCaseResultsRequest(), - parent='parent_value', - ) - - -def test_list_test_case_results_pager(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - next_page_token='abc', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[], - next_page_token='def', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - ], - next_page_token='ghi', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_test_case_results(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, test_case.TestCaseResult) - for i in results) - -def test_list_test_case_results_pages(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - next_page_token='abc', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[], - next_page_token='def', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - ], - next_page_token='ghi', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_test_case_results(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_test_case_results_async_pager(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - next_page_token='abc', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[], - next_page_token='def', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - ], - next_page_token='ghi', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_test_case_results(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, test_case.TestCaseResult) - for i in responses) - -@pytest.mark.asyncio -async def test_list_test_case_results_async_pages(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_test_case_results), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - next_page_token='abc', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[], - next_page_token='def', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - ], - next_page_token='ghi', - ), - test_case.ListTestCaseResultsResponse( - test_case_results=[ - test_case.TestCaseResult(), - test_case.TestCaseResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_test_case_results(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_test_case_result(transport: str = 'grpc', request_type=test_case.GetTestCaseResultRequest): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCaseResult( - name='name_value', - environment='environment_value', - test_result=test_case.TestResult.PASSED, - ) - response = client.get_test_case_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.TestCaseResult) - assert response.name == 'name_value' - assert response.environment == 'environment_value' - assert response.test_result == test_case.TestResult.PASSED - - -def test_get_test_case_result_from_dict(): - test_get_test_case_result(request_type=dict) - - -def test_get_test_case_result_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - client.get_test_case_result() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseResultRequest() - - -@pytest.mark.asyncio -async def test_get_test_case_result_async(transport: str = 'grpc_asyncio', request_type=test_case.GetTestCaseResultRequest): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult( - name='name_value', - environment='environment_value', - test_result=test_case.TestResult.PASSED, - )) - response = await client.get_test_case_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, test_case.TestCaseResult) - assert response.name == 'name_value' - assert response.environment == 'environment_value' - assert response.test_result == test_case.TestResult.PASSED - - -@pytest.mark.asyncio -async def test_get_test_case_result_async_from_dict(): - await test_get_test_case_result_async(request_type=dict) - - -def test_get_test_case_result_field_headers(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.GetTestCaseResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - call.return_value = test_case.TestCaseResult() - client.get_test_case_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_test_case_result_field_headers_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = test_case.GetTestCaseResultRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult()) - await client.get_test_case_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] - - -def test_get_test_case_result_flattened(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCaseResult() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_test_case_result( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -def test_get_test_case_result_flattened_error(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_test_case_result( - test_case.GetTestCaseResultRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_test_case_result_flattened_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_test_case_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = test_case.TestCaseResult() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCaseResult()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_test_case_result( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_test_case_result_flattened_error_async(): - client = TestCasesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_test_case_result( - test_case.GetTestCaseResultRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TestCasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TestCasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TestCasesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TestCasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TestCasesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TestCasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TestCasesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TestCasesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TestCasesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TestCasesGrpcTransport, - transports.TestCasesGrpcAsyncIOTransport, -]) -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 = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TestCasesGrpcTransport, - ) - -def test_test_cases_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TestCasesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_test_cases_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TestCasesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_test_cases', - 'batch_delete_test_cases', - 'get_test_case', - 'create_test_case', - 'update_test_case', - 'run_test_case', - 'batch_run_test_cases', - 'calculate_coverage', - 'import_test_cases', - 'export_test_cases', - 'list_test_case_results', - 'get_test_case_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_test_cases_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TestCasesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_test_cases_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TestCasesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_test_cases_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TestCasesTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_test_cases_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - TestCasesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_test_cases_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - TestCasesClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TestCasesGrpcTransport, - transports.TestCasesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_test_cases_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TestCasesGrpcTransport, - transports.TestCasesGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_test_cases_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TestCasesGrpcTransport, grpc_helpers), - (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_test_cases_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TestCasesGrpcTransport, grpc_helpers), - (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_test_cases_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TestCasesGrpcTransport, grpc_helpers), - (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_test_cases_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) -def test_test_cases_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = 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_test_cases_host_no_port(): - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_test_cases_host_with_port(): - client = TestCasesClient( - 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_test_cases_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TestCasesGrpcTransport( - 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_test_cases_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TestCasesGrpcAsyncIOTransport( - 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.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) -def test_test_cases_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.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport]) -def test_test_cases_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_test_cases_grpc_lro_client(): - client = TestCasesClient( - 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_test_cases_grpc_lro_async_client(): - client = TestCasesAsyncClient( - 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" - location = "clam" - agent = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}".format(project=project, location=location, agent=agent, ) - actual = TestCasesClient.agent_path(project, location, agent) - assert expected == actual - - -def test_parse_agent_path(): - expected = { - "project": "octopus", - "location": "oyster", - "agent": "nudibranch", - } - path = TestCasesClient.agent_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_agent_path(path) - assert expected == actual - -def test_entity_type_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - entity_type = "nautilus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format(project=project, location=location, agent=agent, entity_type=entity_type, ) - actual = TestCasesClient.entity_type_path(project, location, agent, entity_type) - assert expected == actual - - -def test_parse_entity_type_path(): - expected = { - "project": "scallop", - "location": "abalone", - "agent": "squid", - "entity_type": "clam", - } - path = TestCasesClient.entity_type_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_entity_type_path(path) - assert expected == actual - -def test_environment_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - environment = "nudibranch" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format(project=project, location=location, agent=agent, environment=environment, ) - actual = TestCasesClient.environment_path(project, location, agent, environment) - assert expected == actual - - -def test_parse_environment_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "agent": "winkle", - "environment": "nautilus", - } - path = TestCasesClient.environment_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_environment_path(path) - assert expected == actual - -def test_flow_path(): - project = "scallop" - location = "abalone" - agent = "squid" - flow = "clam" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = TestCasesClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "whelk", - "location": "octopus", - "agent": "oyster", - "flow": "nudibranch", - } - path = TestCasesClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_flow_path(path) - assert expected == actual - -def test_intent_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - intent = "nautilus" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = TestCasesClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "scallop", - "location": "abalone", - "agent": "squid", - "intent": "clam", - } - path = TestCasesClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_intent_path(path) - assert expected == actual - -def test_page_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - flow = "nudibranch" - page = "cuttlefish" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - actual = TestCasesClient.page_path(project, location, agent, flow, page) - assert expected == actual - - -def test_parse_page_path(): - expected = { - "project": "mussel", - "location": "winkle", - "agent": "nautilus", - "flow": "scallop", - "page": "abalone", - } - path = TestCasesClient.page_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_page_path(path) - assert expected == actual - -def test_test_case_path(): - project = "squid" - location = "clam" - agent = "whelk" - test_case = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format(project=project, location=location, agent=agent, test_case=test_case, ) - actual = TestCasesClient.test_case_path(project, location, agent, test_case) - assert expected == actual - - -def test_parse_test_case_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "test_case": "mussel", - } - path = TestCasesClient.test_case_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_test_case_path(path) - assert expected == actual - -def test_test_case_result_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - test_case = "abalone" - result = "squid" - expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format(project=project, location=location, agent=agent, test_case=test_case, result=result, ) - actual = TestCasesClient.test_case_result_path(project, location, agent, test_case, result) - assert expected == actual - - -def test_parse_test_case_result_path(): - expected = { - "project": "clam", - "location": "whelk", - "agent": "octopus", - "test_case": "oyster", - "result": "nudibranch", - } - path = TestCasesClient.test_case_result_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_test_case_result_path(path) - assert expected == actual - -def test_transition_route_group_path(): - project = "cuttlefish" - location = "mussel" - agent = "winkle" - flow = "nautilus" - transition_route_group = "scallop" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - actual = TestCasesClient.transition_route_group_path(project, location, agent, flow, transition_route_group) - assert expected == actual - - -def test_parse_transition_route_group_path(): - expected = { - "project": "abalone", - "location": "squid", - "agent": "clam", - "flow": "whelk", - "transition_route_group": "octopus", - } - path = TestCasesClient.transition_route_group_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_transition_route_group_path(path) - assert expected == actual - -def test_webhook_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - webhook = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = TestCasesClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "winkle", - "location": "nautilus", - "agent": "scallop", - "webhook": "abalone", - } - path = TestCasesClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TestCasesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = TestCasesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = TestCasesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = TestCasesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TestCasesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = TestCasesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = TestCasesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = TestCasesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = TestCasesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = TestCasesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TestCasesClient.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.TestCasesTransport, '_prep_wrapped_messages') as prep: - client = TestCasesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TestCasesTransport, '_prep_wrapped_messages') as prep: - transport_class = TestCasesClient.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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py deleted file mode 100644 index 90fbb52c..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py +++ /dev/null @@ -1,2470 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.transition_route_groups import TransitionRouteGroupsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import TransitionRouteGroupsClient -from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import pagers -from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import transports -from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import fulfillment -from google.cloud.dialogflowcx_v3beta1.types import page -from google.cloud.dialogflowcx_v3beta1.types import response_message -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group -from google.cloud.dialogflowcx_v3beta1.types import transition_route_group as gcdc_transition_route_group -from google.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 TransitionRouteGroupsClient._get_default_mtls_endpoint(None) is None - assert TransitionRouteGroupsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TransitionRouteGroupsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TransitionRouteGroupsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TransitionRouteGroupsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TransitionRouteGroupsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - TransitionRouteGroupsClient, - TransitionRouteGroupsAsyncClient, -]) -def test_transition_route_groups_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", [ - TransitionRouteGroupsClient, - TransitionRouteGroupsAsyncClient, -]) -def test_transition_route_groups_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_transition_route_groups_client_get_transport_class(): - transport = TransitionRouteGroupsClient.get_transport_class() - available_transports = [ - transports.TransitionRouteGroupsGrpcTransport, - ] - assert transport in available_transports - - transport = TransitionRouteGroupsClient.get_transport_class("grpc") - assert transport == transports.TransitionRouteGroupsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), - (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(TransitionRouteGroupsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsClient)) -@mock.patch.object(TransitionRouteGroupsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsAsyncClient)) -def test_transition_route_groups_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(TransitionRouteGroupsClient, '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(TransitionRouteGroupsClient, '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", [ - (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc", "true"), - (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc", "false"), - (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(TransitionRouteGroupsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsClient)) -@mock.patch.object(TransitionRouteGroupsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TransitionRouteGroupsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_transition_route_groups_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", [ - (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), - (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_transition_route_groups_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", [ - (TransitionRouteGroupsClient, transports.TransitionRouteGroupsGrpcTransport, "grpc"), - (TransitionRouteGroupsAsyncClient, transports.TransitionRouteGroupsGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_transition_route_groups_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_transition_route_groups_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TransitionRouteGroupsClient( - 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_transition_route_groups(transport: str = 'grpc', request_type=transition_route_group.ListTransitionRouteGroupsRequest): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.ListTransitionRouteGroupsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_transition_route_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransitionRouteGroupsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_transition_route_groups_from_dict(): - test_list_transition_route_groups(request_type=dict) - - -def test_list_transition_route_groups_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TransitionRouteGroupsClient( - credentials=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_transition_route_groups), - '__call__') as call: - client.list_transition_route_groups() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() - - -@pytest.mark.asyncio -async def test_list_transition_route_groups_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.ListTransitionRouteGroupsRequest): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_transition_route_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransitionRouteGroupsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_transition_route_groups_async_from_dict(): - await test_list_transition_route_groups_async(request_type=dict) - - -def test_list_transition_route_groups_field_headers(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.ListTransitionRouteGroupsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() - client.list_transition_route_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_transition_route_groups_field_headers_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.ListTransitionRouteGroupsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse()) - await client.list_transition_route_groups(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_transition_route_groups_flattened(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_transition_route_groups( - parent='parent_value', - ) - - # Establish that the 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_transition_route_groups_flattened_error(): - client = TransitionRouteGroupsClient( - credentials=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_transition_route_groups( - transition_route_group.ListTransitionRouteGroupsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_transition_route_groups_flattened_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.ListTransitionRouteGroupsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_transition_route_groups( - 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_transition_route_groups_flattened_error_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_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_transition_route_groups( - transition_route_group.ListTransitionRouteGroupsRequest(), - parent='parent_value', - ) - - -def test_list_transition_route_groups_pager(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='abc', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[], - next_page_token='def', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='ghi', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_transition_route_groups(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, transition_route_group.TransitionRouteGroup) - for i in results) - -def test_list_transition_route_groups_pages(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='abc', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[], - next_page_token='def', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='ghi', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - ), - RuntimeError, - ) - pages = list(client.list_transition_route_groups(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_transition_route_groups_async_pager(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='abc', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[], - next_page_token='def', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='ghi', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_transition_route_groups(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, transition_route_group.TransitionRouteGroup) - for i in responses) - -@pytest.mark.asyncio -async def test_list_transition_route_groups_async_pages(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_transition_route_groups), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='abc', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[], - next_page_token='def', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - ], - next_page_token='ghi', - ), - transition_route_group.ListTransitionRouteGroupsResponse( - transition_route_groups=[ - transition_route_group.TransitionRouteGroup(), - transition_route_group.TransitionRouteGroup(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_transition_route_groups(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_transition_route_group(transport: str = 'grpc', request_type=transition_route_group.GetTransitionRouteGroupRequest): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - ) - response = client.get_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_get_transition_route_group_from_dict(): - test_get_transition_route_group(request_type=dict) - - -def test_get_transition_route_group_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group), - '__call__') as call: - client.get_transition_route_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() - - -@pytest.mark.asyncio -async def test_get_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.GetTransitionRouteGroupRequest): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - )) - response = await client.get_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_get_transition_route_group_async_from_dict(): - await test_get_transition_route_group_async(request_type=dict) - - -def test_get_transition_route_group_field_headers(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.GetTransitionRouteGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transition_route_group), - '__call__') as call: - call.return_value = transition_route_group.TransitionRouteGroup() - client.get_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_transition_route_group_field_headers_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.GetTransitionRouteGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transition_route_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup()) - await client.get_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_transition_route_group_flattened(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_transition_route_group( - name='name_value', - ) - - # Establish that the 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_transition_route_group_flattened_error(): - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group( - transition_route_group.GetTransitionRouteGroupRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_transition_route_group_flattened_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = transition_route_group.TransitionRouteGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(transition_route_group.TransitionRouteGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_transition_route_group( - 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_transition_route_group_flattened_error_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_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_transition_route_group( - transition_route_group.GetTransitionRouteGroupRequest(), - name='name_value', - ) - - -def test_create_transition_route_group(transport: str = 'grpc', request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - ) - response = client.create_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_create_transition_route_group_from_dict(): - test_create_transition_route_group(request_type=dict) - - -def test_create_transition_route_group_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group), - '__call__') as call: - client.create_transition_route_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() - - -@pytest.mark.asyncio -async def test_create_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - )) - response = await client.create_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_create_transition_route_group_async_from_dict(): - await test_create_transition_route_group_async(request_type=dict) - - -def test_create_transition_route_group_field_headers(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transition_route_group), - '__call__') as call: - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - client.create_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_transition_route_group_field_headers_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transition_route_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) - await client.create_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_transition_route_group_flattened(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_transition_route_group( - parent='parent_value', - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') - - -def test_create_transition_route_group_flattened_error(): - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group( - gcdc_transition_route_group.CreateTransitionRouteGroupRequest(), - parent='parent_value', - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_transition_route_group_flattened_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_transition_route_group( - parent='parent_value', - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') - - -@pytest.mark.asyncio -async def test_create_transition_route_group_flattened_error_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_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_transition_route_group( - gcdc_transition_route_group.CreateTransitionRouteGroupRequest(), - parent='parent_value', - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), - ) - - -def test_update_transition_route_group(transport: str = 'grpc', request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - ) - response = client.update_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_transition_route_group_from_dict(): - test_update_transition_route_group(request_type=dict) - - -def test_update_transition_route_group_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group), - '__call__') as call: - client.update_transition_route_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() - - -@pytest.mark.asyncio -async def test_update_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_transition_route_group_async_from_dict(): - await test_update_transition_route_group_async(request_type=dict) - - -def test_update_transition_route_group_field_headers(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() - - request.transition_route_group.name = 'transition_route_group.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transition_route_group), - '__call__') as call: - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - client.update_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'transition_route_group.name=transition_route_group.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_transition_route_group_field_headers_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() - - request.transition_route_group.name = 'transition_route_group.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transition_route_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) - await client.update_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'transition_route_group.name=transition_route_group.name/value', - ) in kw['metadata'] - - -def test_update_transition_route_group_flattened(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_transition_route_group( - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_transition_route_group_flattened_error(): - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group( - gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(), - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_transition_route_group_flattened_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_transition_route_group.TransitionRouteGroup()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_transition_route_group( - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(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].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_transition_route_group_flattened_error_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_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_transition_route_group( - gcdc_transition_route_group.UpdateTransitionRouteGroupRequest(), - transition_route_group=gcdc_transition_route_group.TransitionRouteGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_transition_route_group(transport: str = 'grpc', request_type=transition_route_group.DeleteTransitionRouteGroupRequest): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_transition_route_group_from_dict(): - test_delete_transition_route_group(request_type=dict) - - -def test_delete_transition_route_group_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group), - '__call__') as call: - client.delete_transition_route_group() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() - - -@pytest.mark.asyncio -async def test_delete_transition_route_group_async(transport: str = 'grpc_asyncio', request_type=transition_route_group.DeleteTransitionRouteGroupRequest): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_transition_route_group), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_transition_route_group_async_from_dict(): - await test_delete_transition_route_group_async(request_type=dict) - - -def test_delete_transition_route_group_field_headers(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.DeleteTransitionRouteGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transition_route_group), - '__call__') as call: - call.return_value = None - client.delete_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_transition_route_group_field_headers_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = transition_route_group.DeleteTransitionRouteGroupRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transition_route_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_transition_route_group(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_transition_route_group_flattened(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transition_route_group), - '__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_transition_route_group( - 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_transition_route_group_flattened_error(): - client = TransitionRouteGroupsClient( - credentials=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_transition_route_group( - transition_route_group.DeleteTransitionRouteGroupRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_transition_route_group_flattened_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_transition_route_group), - '__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_transition_route_group( - 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_transition_route_group_flattened_error_async(): - client = TransitionRouteGroupsAsyncClient( - credentials=ga_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_transition_route_group( - transition_route_group.DeleteTransitionRouteGroupRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TransitionRouteGroupsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TransitionRouteGroupsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TransitionRouteGroupsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TransitionRouteGroupsGrpcTransport, - transports.TransitionRouteGroupsGrpcAsyncIOTransport, -]) -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 = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TransitionRouteGroupsGrpcTransport, - ) - -def test_transition_route_groups_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TransitionRouteGroupsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_transition_route_groups_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TransitionRouteGroupsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_transition_route_groups', - 'get_transition_route_group', - 'create_transition_route_group', - 'update_transition_route_group', - 'delete_transition_route_group', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_transition_route_groups_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TransitionRouteGroupsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TransitionRouteGroupsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_transition_route_groups_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TransitionRouteGroupsTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_transition_route_groups_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - TransitionRouteGroupsClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - TransitionRouteGroupsClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TransitionRouteGroupsGrpcTransport, - transports.TransitionRouteGroupsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_transition_route_groups_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TransitionRouteGroupsGrpcTransport, - transports.TransitionRouteGroupsGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_transition_route_groups_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), - (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_transition_route_groups_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), - (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_transition_route_groups_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), - (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_transition_route_groups_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) -def test_transition_route_groups_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_transition_route_groups_host_no_port(): - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_transition_route_groups_host_with_port(): - client = TransitionRouteGroupsClient( - 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_transition_route_groups_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TransitionRouteGroupsGrpcTransport( - 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_transition_route_groups_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport( - 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.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) -def test_transition_route_groups_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.TransitionRouteGroupsGrpcTransport, transports.TransitionRouteGroupsGrpcAsyncIOTransport]) -def test_transition_route_groups_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_flow_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format(project=project, location=location, agent=agent, flow=flow, ) - actual = TransitionRouteGroupsClient.flow_path(project, location, agent, flow) - assert expected == actual - - -def test_parse_flow_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "flow": "mussel", - } - path = TransitionRouteGroupsClient.flow_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_flow_path(path) - assert expected == actual - -def test_intent_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - intent = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(project=project, location=location, agent=agent, intent=intent, ) - actual = TransitionRouteGroupsClient.intent_path(project, location, agent, intent) - assert expected == actual - - -def test_parse_intent_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "intent": "octopus", - } - path = TransitionRouteGroupsClient.intent_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_intent_path(path) - assert expected == actual - -def test_page_path(): - project = "oyster" - location = "nudibranch" - agent = "cuttlefish" - flow = "mussel" - page = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format(project=project, location=location, agent=agent, flow=flow, page=page, ) - actual = TransitionRouteGroupsClient.page_path(project, location, agent, flow, page) - assert expected == actual - - -def test_parse_page_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "agent": "abalone", - "flow": "squid", - "page": "clam", - } - path = TransitionRouteGroupsClient.page_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_page_path(path) - assert expected == actual - -def test_transition_route_group_path(): - project = "whelk" - location = "octopus" - agent = "oyster" - flow = "nudibranch" - transition_route_group = "cuttlefish" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format(project=project, location=location, agent=agent, flow=flow, transition_route_group=transition_route_group, ) - actual = TransitionRouteGroupsClient.transition_route_group_path(project, location, agent, flow, transition_route_group) - assert expected == actual - - -def test_parse_transition_route_group_path(): - expected = { - "project": "mussel", - "location": "winkle", - "agent": "nautilus", - "flow": "scallop", - "transition_route_group": "abalone", - } - path = TransitionRouteGroupsClient.transition_route_group_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_transition_route_group_path(path) - assert expected == actual - -def test_webhook_path(): - project = "squid" - location = "clam" - agent = "whelk" - webhook = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = TransitionRouteGroupsClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "webhook": "mussel", - } - path = TransitionRouteGroupsClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TransitionRouteGroupsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = TransitionRouteGroupsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = TransitionRouteGroupsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = TransitionRouteGroupsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TransitionRouteGroupsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = TransitionRouteGroupsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = TransitionRouteGroupsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = TransitionRouteGroupsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.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 = TransitionRouteGroupsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = TransitionRouteGroupsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TransitionRouteGroupsClient.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.TransitionRouteGroupsTransport, '_prep_wrapped_messages') as prep: - client = TransitionRouteGroupsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TransitionRouteGroupsTransport, '_prep_wrapped_messages') as prep: - transport_class = TransitionRouteGroupsClient.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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py deleted file mode 100644 index a76f2996..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py +++ /dev/null @@ -1,2658 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.versions import VersionsAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.versions import VersionsClient -from google.cloud.dialogflowcx_v3beta1.services.versions import pagers -from google.cloud.dialogflowcx_v3beta1.services.versions import transports -from google.cloud.dialogflowcx_v3beta1.services.versions.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.versions.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import flow -from google.cloud.dialogflowcx_v3beta1.types import version -from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # 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(): - 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.dialogflowcx_v3beta1.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', - display_name='display_name_value', - description='description_value', - state=version.Version.State.RUNNING, - ) - response = client.get_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == version.GetVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, version.Version) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == version.Version.State.RUNNING - - -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', - display_name='display_name_value', - description='description_value', - state=version.Version.State.RUNNING, - )) - response = await client.get_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == version.GetVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, version.Version) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == version.Version.State.RUNNING - - -@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=gcdc_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 = operations_pb2.Operation(name='operations/spam') - response = client.create_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.CreateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -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] == gcdc_version.CreateVersionRequest() - - -@pytest.mark.asyncio -async def test_create_version_async(transport: str = 'grpc_asyncio', request_type=gcdc_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( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.CreateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@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 = gcdc_version.CreateVersionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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 = gcdc_version.CreateVersionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - 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 = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_version( - parent='parent_value', - version=gcdc_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 == gcdc_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( - gcdc_version.CreateVersionRequest(), - parent='parent_value', - version=gcdc_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 = 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_version( - parent='parent_value', - version=gcdc_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 == gcdc_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( - gcdc_version.CreateVersionRequest(), - parent='parent_value', - version=gcdc_version.Version(name='name_value'), - ) - - -def test_update_version(transport: str = 'grpc', request_type=gcdc_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 = gcdc_version.Version( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_version.Version.State.RUNNING, - ) - response = client.update_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.UpdateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_version.Version) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_version.Version.State.RUNNING - - -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] == gcdc_version.UpdateVersionRequest() - - -@pytest.mark.asyncio -async def test_update_version_async(transport: str = 'grpc_asyncio', request_type=gcdc_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(gcdc_version.Version( - name='name_value', - display_name='display_name_value', - description='description_value', - state=gcdc_version.Version.State.RUNNING, - )) - response = await client.update_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.UpdateVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_version.Version) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == gcdc_version.Version.State.RUNNING - - -@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 = gcdc_version.UpdateVersionRequest() - - request.version.name = 'version.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: - call.return_value = gcdc_version.Version() - client.update_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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 = gcdc_version.UpdateVersionRequest() - - request.version.name = 'version.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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 = gcdc_version.Version() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_version( - version=gcdc_version.Version(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].version == gcdc_version.Version(name='name_value') - assert args[0].update_mask == field_mask_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( - gcdc_version.UpdateVersionRequest(), - version=gcdc_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 = gcdc_version.Version() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_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=gcdc_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 == gcdc_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( - gcdc_version.UpdateVersionRequest(), - version=gcdc_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_load_version(transport: str = 'grpc', request_type=version.LoadVersionRequest): - 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.load_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.load_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == version.LoadVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_load_version_from_dict(): - test_load_version(request_type=dict) - - -def test_load_version_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_version), - '__call__') as call: - client.load_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == version.LoadVersionRequest() - - -@pytest.mark.asyncio -async def test_load_version_async(transport: str = 'grpc_asyncio', request_type=version.LoadVersionRequest): - 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.load_version), - '__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.load_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == version.LoadVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_load_version_async_from_dict(): - await test_load_version_async(request_type=dict) - - -def test_load_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.LoadVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_version), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.load_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_load_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.LoadVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.load_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_load_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.load_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.load_version( - name='name_value', - ) - - # Establish that the 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_load_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.load_version( - version.LoadVersionRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_load_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.load_version), - '__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.load_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_load_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.load_version( - version.LoadVersionRequest(), - 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.dialogflowcx_v3beta1.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', - 'load_version', - ) - 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_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.dialogflowcx_v3beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VersionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_versions_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VersionsTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - 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.dialogflowcx_v3beta1.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_versions_grpc_lro_client(): - client = VersionsClient( - 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_versions_grpc_lro_async_client(): - client = VersionsAsyncClient( - 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_version_path(): - project = "squid" - location = "clam" - agent = "whelk" - flow = "octopus" - version = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format(project=project, location=location, agent=agent, flow=flow, version=version, ) - actual = VersionsClient.version_path(project, location, agent, flow, version) - assert expected == actual - - -def test_parse_version_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "agent": "mussel", - "flow": "winkle", - "version": "nautilus", - } - 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 = "scallop" - 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": "abalone", - } - 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 = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = VersionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - 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 = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = VersionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - 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 = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = VersionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - 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 = "cuttlefish" - location = "mussel" - 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": "winkle", - "location": "nautilus", - } - 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/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py b/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py deleted file mode 100644 index d4598d7c..00000000 --- a/owl-bot-staging/v3beta1/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py +++ /dev/null @@ -1,2409 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.dialogflowcx_v3beta1.services.webhooks import WebhooksAsyncClient -from google.cloud.dialogflowcx_v3beta1.services.webhooks import WebhooksClient -from google.cloud.dialogflowcx_v3beta1.services.webhooks import pagers -from google.cloud.dialogflowcx_v3beta1.services.webhooks import transports -from google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.base import _API_CORE_VERSION -from google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.dialogflowcx_v3beta1.types import webhook -from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # 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(): - 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 WebhooksClient._get_default_mtls_endpoint(None) is None - assert WebhooksClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert WebhooksClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert WebhooksClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert WebhooksClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert WebhooksClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - WebhooksClient, - WebhooksAsyncClient, -]) -def test_webhooks_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", [ - WebhooksClient, - WebhooksAsyncClient, -]) -def test_webhooks_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_webhooks_client_get_transport_class(): - transport = WebhooksClient.get_transport_class() - available_transports = [ - transports.WebhooksGrpcTransport, - ] - assert transport in available_transports - - transport = WebhooksClient.get_transport_class("grpc") - assert transport == transports.WebhooksGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), - (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(WebhooksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksClient)) -@mock.patch.object(WebhooksAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksAsyncClient)) -def test_webhooks_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(WebhooksClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=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(WebhooksClient, '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", [ - (WebhooksClient, transports.WebhooksGrpcTransport, "grpc", "true"), - (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (WebhooksClient, transports.WebhooksGrpcTransport, "grpc", "false"), - (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(WebhooksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksClient)) -@mock.patch.object(WebhooksAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(WebhooksAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_webhooks_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", [ - (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), - (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_webhooks_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", [ - (WebhooksClient, transports.WebhooksGrpcTransport, "grpc"), - (WebhooksAsyncClient, transports.WebhooksGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_webhooks_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_webhooks_client_client_options_from_dict(): - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = WebhooksClient( - 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_webhooks(transport: str = 'grpc', request_type=webhook.ListWebhooksRequest): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhooks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.ListWebhooksResponse( - next_page_token='next_page_token_value', - ) - response = client.list_webhooks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWebhooksPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_webhooks_from_dict(): - test_list_webhooks(request_type=dict) - - -def test_list_webhooks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebhooksClient( - credentials=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_webhooks), - '__call__') as call: - client.list_webhooks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() - - -@pytest.mark.asyncio -async def test_list_webhooks_async(transport: str = 'grpc_asyncio', request_type=webhook.ListWebhooksRequest): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhooks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_webhooks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWebhooksAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_webhooks_async_from_dict(): - await test_list_webhooks_async(request_type=dict) - - -def test_list_webhooks_field_headers(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.ListWebhooksRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - call.return_value = webhook.ListWebhooksResponse() - client.list_webhooks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_webhooks_field_headers_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.ListWebhooksRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse()) - await client.list_webhooks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_webhooks_flattened(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.ListWebhooksResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_webhooks( - parent='parent_value', - ) - - # Establish that the 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_webhooks_flattened_error(): - client = WebhooksClient( - credentials=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_webhooks( - webhook.ListWebhooksRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_webhooks_flattened_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.ListWebhooksResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.ListWebhooksResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_webhooks( - 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_webhooks_flattened_error_async(): - client = WebhooksAsyncClient( - credentials=ga_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_webhooks( - webhook.ListWebhooksRequest(), - parent='parent_value', - ) - - -def test_list_webhooks_pager(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - webhook.Webhook(), - ], - next_page_token='abc', - ), - webhook.ListWebhooksResponse( - webhooks=[], - next_page_token='def', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - ], - next_page_token='ghi', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_webhooks(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, webhook.Webhook) - for i in results) - -def test_list_webhooks_pages(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - webhook.Webhook(), - ], - next_page_token='abc', - ), - webhook.ListWebhooksResponse( - webhooks=[], - next_page_token='def', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - ], - next_page_token='ghi', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - ], - ), - RuntimeError, - ) - pages = list(client.list_webhooks(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_webhooks_async_pager(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - webhook.Webhook(), - ], - next_page_token='abc', - ), - webhook.ListWebhooksResponse( - webhooks=[], - next_page_token='def', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - ], - next_page_token='ghi', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_webhooks(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, webhook.Webhook) - for i in responses) - -@pytest.mark.asyncio -async def test_list_webhooks_async_pages(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_webhooks), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - webhook.Webhook(), - ], - next_page_token='abc', - ), - webhook.ListWebhooksResponse( - webhooks=[], - next_page_token='def', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - ], - next_page_token='ghi', - ), - webhook.ListWebhooksResponse( - webhooks=[ - webhook.Webhook(), - webhook.Webhook(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_webhooks(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_webhook(transport: str = 'grpc', request_type=webhook.GetWebhookRequest): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - generic_web_service=webhook.Webhook.GenericWebService(uri='uri_value'), - ) - response = client.get_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -def test_get_webhook_from_dict(): - test_get_webhook(request_type=dict) - - -def test_get_webhook_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebhooksClient( - credentials=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_webhook), - '__call__') as call: - client.get_webhook() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() - - -@pytest.mark.asyncio -async def test_get_webhook_async(transport: str = 'grpc_asyncio', request_type=webhook.GetWebhookRequest): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - )) - response = await client.get_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -@pytest.mark.asyncio -async def test_get_webhook_async_from_dict(): - await test_get_webhook_async(request_type=dict) - - -def test_get_webhook_field_headers(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.GetWebhookRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_webhook), - '__call__') as call: - call.return_value = webhook.Webhook() - client.get_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_webhook_field_headers_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.GetWebhookRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_webhook), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook()) - await client.get_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_webhook_flattened(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.Webhook() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_webhook( - name='name_value', - ) - - # Establish that the 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_webhook_flattened_error(): - client = WebhooksClient( - credentials=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_webhook( - webhook.GetWebhookRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_webhook_flattened_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = webhook.Webhook() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_webhook( - 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_webhook_flattened_error_async(): - client = WebhooksAsyncClient( - credentials=ga_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_webhook( - webhook.GetWebhookRequest(), - name='name_value', - ) - - -def test_create_webhook(transport: str = 'grpc', request_type=gcdc_webhook.CreateWebhookRequest): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri='uri_value'), - ) - response = client.create_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -def test_create_webhook_from_dict(): - test_create_webhook(request_type=dict) - - -def test_create_webhook_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebhooksClient( - credentials=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_webhook), - '__call__') as call: - client.create_webhook() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() - - -@pytest.mark.asyncio -async def test_create_webhook_async(transport: str = 'grpc_asyncio', request_type=gcdc_webhook.CreateWebhookRequest): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - )) - response = await client.create_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -@pytest.mark.asyncio -async def test_create_webhook_async_from_dict(): - await test_create_webhook_async(request_type=dict) - - -def test_create_webhook_field_headers(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_webhook.CreateWebhookRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_webhook), - '__call__') as call: - call.return_value = gcdc_webhook.Webhook() - client.create_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header 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_webhook_field_headers_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_webhook.CreateWebhookRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_webhook), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) - await client.create_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish 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_webhook_flattened(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_webhook( - parent='parent_value', - webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') - - -def test_create_webhook_flattened_error(): - client = WebhooksClient( - credentials=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_webhook( - gcdc_webhook.CreateWebhookRequest(), - parent='parent_value', - webhook=gcdc_webhook.Webhook(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_webhook_flattened_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_webhook( - parent='parent_value', - webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') - - -@pytest.mark.asyncio -async def test_create_webhook_flattened_error_async(): - client = WebhooksAsyncClient( - credentials=ga_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_webhook( - gcdc_webhook.CreateWebhookRequest(), - parent='parent_value', - webhook=gcdc_webhook.Webhook(name='name_value'), - ) - - -def test_update_webhook(transport: str = 'grpc', request_type=gcdc_webhook.UpdateWebhookRequest): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri='uri_value'), - ) - response = client.update_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -def test_update_webhook_from_dict(): - test_update_webhook(request_type=dict) - - -def test_update_webhook_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebhooksClient( - credentials=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_webhook), - '__call__') as call: - client.update_webhook() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() - - -@pytest.mark.asyncio -async def test_update_webhook_async(transport: str = 'grpc_asyncio', request_type=gcdc_webhook.UpdateWebhookRequest): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook( - name='name_value', - display_name='display_name_value', - disabled=True, - )) - response = await client.update_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.disabled is True - - -@pytest.mark.asyncio -async def test_update_webhook_async_from_dict(): - await test_update_webhook_async(request_type=dict) - - -def test_update_webhook_field_headers(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_webhook.UpdateWebhookRequest() - - request.webhook.name = 'webhook.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_webhook), - '__call__') as call: - call.return_value = gcdc_webhook.Webhook() - client.update_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'webhook.name=webhook.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_webhook_field_headers_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcdc_webhook.UpdateWebhookRequest() - - request.webhook.name = 'webhook.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_webhook), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) - await client.update_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'webhook.name=webhook.name/value', - ) in kw['metadata'] - - -def test_update_webhook_flattened(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_webhook( - webhook=gcdc_webhook.Webhook(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].webhook == gcdc_webhook.Webhook(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_webhook_flattened_error(): - client = WebhooksClient( - credentials=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_webhook( - gcdc_webhook.UpdateWebhookRequest(), - webhook=gcdc_webhook.Webhook(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_webhook_flattened_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcdc_webhook.Webhook() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_webhook.Webhook()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_webhook( - webhook=gcdc_webhook.Webhook(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].webhook == gcdc_webhook.Webhook(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_webhook_flattened_error_async(): - client = WebhooksAsyncClient( - credentials=ga_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_webhook( - gcdc_webhook.UpdateWebhookRequest(), - webhook=gcdc_webhook.Webhook(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_webhook(transport: str = 'grpc', request_type=webhook.DeleteWebhookRequest): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_webhook_from_dict(): - test_delete_webhook(request_type=dict) - - -def test_delete_webhook_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = WebhooksClient( - credentials=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_webhook), - '__call__') as call: - client.delete_webhook() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() - - -@pytest.mark.asyncio -async def test_delete_webhook_async(transport: str = 'grpc_asyncio', request_type=webhook.DeleteWebhookRequest): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_webhook_async_from_dict(): - await test_delete_webhook_async(request_type=dict) - - -def test_delete_webhook_field_headers(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.DeleteWebhookRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_webhook), - '__call__') as call: - call.return_value = None - client.delete_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_webhook_field_headers_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = webhook.DeleteWebhookRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_webhook), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_webhook(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_webhook_flattened(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_webhook), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_webhook( - name='name_value', - ) - - # Establish that the 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_webhook_flattened_error(): - client = WebhooksClient( - credentials=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_webhook( - webhook.DeleteWebhookRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_webhook_flattened_async(): - client = WebhooksAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_webhook), - '__call__') as call: - # 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_webhook( - 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_webhook_flattened_error_async(): - client = WebhooksAsyncClient( - credentials=ga_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_webhook( - webhook.DeleteWebhookRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebhooksGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebhooksGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebhooksClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.WebhooksGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebhooksClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebhooksGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = WebhooksClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebhooksGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.WebhooksGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.WebhooksGrpcTransport, - transports.WebhooksGrpcAsyncIOTransport, -]) -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 = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.WebhooksGrpcTransport, - ) - -def test_webhooks_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebhooksTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_webhooks_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.WebhooksTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_webhooks', - 'get_webhook', - 'create_webhook', - 'update_webhook', - 'delete_webhook', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -@requires_google_auth_gte_1_25_0 -def test_webhooks_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebhooksTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_webhooks_base_transport_with_credentials_file_old_google_auth(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebhooksTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', - ), - quota_project_id="octopus", - ) - - -def test_webhooks_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebhooksTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_webhooks_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - WebhooksClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_webhooks_auth_adc_old_google_auth(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - WebhooksClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebhooksGrpcTransport, - transports.WebhooksGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_webhooks_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/dialogflow',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebhooksGrpcTransport, - transports.WebhooksGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_webhooks_transport_auth_adc_old_google_auth(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.WebhooksGrpcTransport, grpc_helpers), - (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_gte_1_26_0 -def test_webhooks_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - scopes=["1", "2"], - default_host="dialogflow.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.WebhooksGrpcTransport, grpc_helpers), - (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_webhooks_transport_create_channel_old_api_core(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus") - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/dialogflow', -), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.WebhooksGrpcTransport, grpc_helpers), - (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -@requires_api_core_lt_1_26_0 -def test_webhooks_transport_create_channel_user_scopes(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - - create_channel.assert_called_with( - "dialogflow.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) -def test_webhooks_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = 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_webhooks_host_no_port(): - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='dialogflow.googleapis.com'), - ) - assert client.transport._host == 'dialogflow.googleapis.com:443' - - -def test_webhooks_host_with_port(): - client = WebhooksClient( - 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_webhooks_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebhooksGrpcTransport( - 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_webhooks_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.WebhooksGrpcAsyncIOTransport( - 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.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) -def test_webhooks_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.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport]) -def test_webhooks_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_service_path(): - project = "squid" - location = "clam" - namespace = "whelk" - service = "octopus" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - actual = WebhooksClient.service_path(project, location, namespace, service) - assert expected == actual - - -def test_parse_service_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "namespace": "cuttlefish", - "service": "mussel", - } - path = WebhooksClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.parse_service_path(path) - assert expected == actual - -def test_webhook_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - webhook = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format(project=project, location=location, agent=agent, webhook=webhook, ) - actual = WebhooksClient.webhook_path(project, location, agent, webhook) - assert expected == actual - - -def test_parse_webhook_path(): - expected = { - "project": "squid", - "location": "clam", - "agent": "whelk", - "webhook": "octopus", - } - path = WebhooksClient.webhook_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.parse_webhook_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = WebhooksClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = WebhooksClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = WebhooksClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = WebhooksClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = WebhooksClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = WebhooksClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = WebhooksClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = WebhooksClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.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 = WebhooksClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = WebhooksClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = WebhooksClient.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.WebhooksTransport, '_prep_wrapped_messages') as prep: - client = WebhooksClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.WebhooksTransport, '_prep_wrapped_messages') as prep: - transport_class = WebhooksClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py index 44ff5fbf..fd6bc8a6 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py @@ -2061,6 +2061,533 @@ async def test_lookup_environment_history_async_pages(): assert page_.raw_page.next_page_token == token +def test_run_continuous_test( + transport: str = "grpc", request_type=environment.RunContinuousTestRequest +): + 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.run_continuous_test), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.run_continuous_test(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.RunContinuousTestRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_continuous_test_from_dict(): + test_run_continuous_test(request_type=dict) + + +def test_run_continuous_test_empty_call(): + # 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.run_continuous_test), "__call__" + ) as call: + client.run_continuous_test() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.RunContinuousTestRequest() + + +@pytest.mark.asyncio +async def test_run_continuous_test_async( + transport: str = "grpc_asyncio", request_type=environment.RunContinuousTestRequest +): + 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.run_continuous_test), "__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.run_continuous_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.RunContinuousTestRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_continuous_test_async_from_dict(): + await test_run_continuous_test_async(request_type=dict) + + +def test_run_continuous_test_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.RunContinuousTestRequest() + + request.environment = "environment/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_continuous_test), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.run_continuous_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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=environment/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_run_continuous_test_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.RunContinuousTestRequest() + + request.environment = "environment/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_continuous_test), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.run_continuous_test(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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=environment/value",) in kw["metadata"] + + +def test_list_continuous_test_results( + transport: str = "grpc", request_type=environment.ListContinuousTestResultsRequest +): + 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_continuous_test_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListContinuousTestResultsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_continuous_test_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListContinuousTestResultsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListContinuousTestResultsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_continuous_test_results_from_dict(): + test_list_continuous_test_results(request_type=dict) + + +def test_list_continuous_test_results_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = 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_continuous_test_results), "__call__" + ) as call: + client.list_continuous_test_results() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListContinuousTestResultsRequest() + + +@pytest.mark.asyncio +async def test_list_continuous_test_results_async( + transport: str = "grpc_asyncio", + request_type=environment.ListContinuousTestResultsRequest, +): + 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_continuous_test_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.ListContinuousTestResultsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_continuous_test_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == environment.ListContinuousTestResultsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListContinuousTestResultsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_continuous_test_results_async_from_dict(): + await test_list_continuous_test_results_async(request_type=dict) + + +def test_list_continuous_test_results_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.ListContinuousTestResultsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_continuous_test_results), "__call__" + ) as call: + call.return_value = environment.ListContinuousTestResultsResponse() + client.list_continuous_test_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_continuous_test_results_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.ListContinuousTestResultsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_continuous_test_results), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.ListContinuousTestResultsResponse() + ) + await client.list_continuous_test_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_continuous_test_results_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_continuous_test_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListContinuousTestResultsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_continuous_test_results(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_continuous_test_results_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_continuous_test_results( + environment.ListContinuousTestResultsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_continuous_test_results_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_continuous_test_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListContinuousTestResultsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.ListContinuousTestResultsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_continuous_test_results(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_continuous_test_results_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_continuous_test_results( + environment.ListContinuousTestResultsRequest(), parent="parent_value", + ) + + +def test_list_continuous_test_results_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_continuous_test_results), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + next_page_token="abc", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[], next_page_token="def", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[environment.ContinuousTestResult(),], + next_page_token="ghi", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_continuous_test_results(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.ContinuousTestResult) for i in results) + + +def test_list_continuous_test_results_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_continuous_test_results), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + next_page_token="abc", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[], next_page_token="def", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[environment.ContinuousTestResult(),], + next_page_token="ghi", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_continuous_test_results(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_continuous_test_results_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_continuous_test_results), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + next_page_token="abc", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[], next_page_token="def", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[environment.ContinuousTestResult(),], + next_page_token="ghi", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_continuous_test_results(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.ContinuousTestResult) for i in responses) + + +@pytest.mark.asyncio +async def test_list_continuous_test_results_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_continuous_test_results), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + next_page_token="abc", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[], next_page_token="def", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[environment.ContinuousTestResult(),], + next_page_token="ghi", + ), + environment.ListContinuousTestResultsResponse( + continuous_test_results=[ + environment.ContinuousTestResult(), + environment.ContinuousTestResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_continuous_test_results(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( @@ -2164,6 +2691,8 @@ def test_environments_base_transport(): "update_environment", "delete_environment", "lookup_environment_history", + "run_continuous_test", + "list_continuous_test_results", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2639,11 +3168,45 @@ def test_environments_grpc_lro_async_client(): assert transport.operations_client is transport.operations_client -def test_environment_path(): +def test_continuous_test_result_path(): project = "squid" location = "clam" agent = "whelk" environment = "octopus" + continuous_test_result = "oyster" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/continuousTestResults/{continuous_test_result}".format( + project=project, + location=location, + agent=agent, + environment=environment, + continuous_test_result=continuous_test_result, + ) + actual = EnvironmentsClient.continuous_test_result_path( + project, location, agent, environment, continuous_test_result + ) + assert expected == actual + + +def test_parse_continuous_test_result_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "agent": "mussel", + "environment": "winkle", + "continuous_test_result": "nautilus", + } + path = EnvironmentsClient.continuous_test_result_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_continuous_test_result_path(path) + assert expected == actual + + +def test_environment_path(): + project = "scallop" + location = "abalone" + agent = "squid" + environment = "clam" expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( project=project, location=location, agent=agent, environment=environment, ) @@ -2653,10 +3216,10 @@ def test_environment_path(): def test_parse_environment_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "environment": "mussel", + "project": "whelk", + "location": "octopus", + "agent": "oyster", + "environment": "nudibranch", } path = EnvironmentsClient.environment_path(**expected) @@ -2665,12 +3228,46 @@ def test_parse_environment_path(): assert expected == actual +def test_test_case_result_path(): + project = "cuttlefish" + location = "mussel" + agent = "winkle" + test_case = "nautilus" + result = "scallop" + expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( + project=project, + location=location, + agent=agent, + test_case=test_case, + result=result, + ) + actual = EnvironmentsClient.test_case_result_path( + project, location, agent, test_case, result + ) + assert expected == actual + + +def test_parse_test_case_result_path(): + expected = { + "project": "abalone", + "location": "squid", + "agent": "clam", + "test_case": "whelk", + "result": "octopus", + } + path = EnvironmentsClient.test_case_result_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_test_case_result_path(path) + assert expected == actual + + def test_version_path(): - project = "winkle" - location = "nautilus" - agent = "scallop" - flow = "abalone" - version = "squid" + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + flow = "mussel" + version = "winkle" expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @@ -2680,11 +3277,11 @@ def test_version_path(): def test_parse_version_path(): expected = { - "project": "clam", - "location": "whelk", - "agent": "octopus", - "flow": "oyster", - "version": "nudibranch", + "project": "nautilus", + "location": "scallop", + "agent": "abalone", + "flow": "squid", + "version": "clam", } path = EnvironmentsClient.version_path(**expected) @@ -2694,7 +3291,7 @@ def test_parse_version_path(): def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2704,7 +3301,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "octopus", } path = EnvironmentsClient.common_billing_account_path(**expected) @@ -2714,7 +3311,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "oyster" expected = "folders/{folder}".format(folder=folder,) actual = EnvironmentsClient.common_folder_path(folder) assert expected == actual @@ -2722,7 +3319,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "nudibranch", } path = EnvironmentsClient.common_folder_path(**expected) @@ -2732,7 +3329,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "cuttlefish" expected = "organizations/{organization}".format(organization=organization,) actual = EnvironmentsClient.common_organization_path(organization) assert expected == actual @@ -2740,7 +3337,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "mussel", } path = EnvironmentsClient.common_organization_path(**expected) @@ -2750,7 +3347,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "winkle" expected = "projects/{project}".format(project=project,) actual = EnvironmentsClient.common_project_path(project) assert expected == actual @@ -2758,7 +3355,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "nautilus", } path = EnvironmentsClient.common_project_path(**expected) @@ -2768,8 +3365,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "scallop" + location = "abalone" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2779,8 +3376,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "squid", + "location": "clam", } path = EnvironmentsClient.common_location_path(**expected)